Skip to content

Commit 1ab148f

Browse files
Solution Leetcode and Explaination Every single line"
1 parent 1bc4a06 commit 1ab148f

File tree

2 files changed

+74
-0
lines changed

2 files changed

+74
-0
lines changed
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
LeetCode 2200 – Find All K-Distant Indices
2+
3+
class Solution {
4+
public List<Integer> findKDistantIndices(int[] nums, int key, int k) {
5+
List<Integer> result = new ArrayList<>();
6+
7+
for (int i = 0; i < nums.length; i++) {
8+
for (int j = Math.max(0, i - k); j <= Math.min(nums.length - 1, i + k); j++) {
9+
if (nums[j] == key) {
10+
result.add(i);
11+
break;
12+
}
13+
}
14+
}
15+
16+
return result;
17+
}
18+
}
19+
20+
Explanation
21+
22+
List<Integer> result = new ArrayList<>();
23+
🔹 Result store karne ke liye list banayi.
24+
25+
Outer loop: i = 0 to nums.length - 1
26+
🔹 Har index i ke liye check karenge ki kya vo k-distant hai kisi key wale index se.
27+
28+
Inner loop: j = i - k to i + k
29+
🔹 i ke aaspas ke sabhi valid indices check karenge (boundary handle bhi kar rahe hain).
30+
31+
if (nums[j] == key)
32+
🔹 Agar key mil gaya, to i k-distant index hai.
33+
34+
result.add(i);
35+
🔹 Result list me i add kar diya.
36+
37+
break;
38+
🔹 Key mil gaya to inner loop break kar do (further check nahi chahiye).
39+
40+
Return result;
41+
🔹 Final answer list return kar di.
42+
43+
Example
44+
Input: nums = [3,4,9,1,3,9,5], key = 9, k = 1
45+
46+
Output: [1,2,3,4,5,6]
47+
🔹 Index 2 & 5 par key=9 hai
48+
🔹 Toh inke ±1 range ke sabhi indices answer me aate hain
49+
50+
Time and Space Complexity
51+
Metric Complexity
52+
Time O(n * k)
53+
Space O(n)
54+
55+
Efficient for small k (since problem allows small arrays).
56+
57+
🔗 Need more help or Java tricks?
58+
https://www.linkedin.com/in/saurabh884095/
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
class Solution {
2+
public List<Integer> findKDistantIndices(int[] nums, int key, int k) {
3+
List<Integer> result = new ArrayList<>();
4+
5+
for (int i = 0; i < nums.length; i++) {
6+
for (int j = Math.max(0, i - k); j <= Math.min(nums.length - 1, i + k); j++) {
7+
if (nums[j] == key) {
8+
result.add(i);
9+
break;
10+
}
11+
}
12+
}
13+
14+
return result;
15+
}
16+
}

0 commit comments

Comments
 (0)