Skip to content

Commit a868ffd

Browse files
feat(recursion-solutions): add solution for all occurrences problem
1 parent 1d928fa commit a868ffd

1 file changed

Lines changed: 29 additions & 0 deletions

File tree

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
/*
2+
PROBLEM:
3+
Find all indices of a given key in an array using recursion.
4+
5+
APPROACH:
6+
Traverse array using index.
7+
If match → print index.
8+
Continue recursion till end.
9+
*/
10+
11+
public class AllOccurrences {
12+
13+
public static void printAll(int[] arr, int key, int i) {
14+
if (i == arr.length) {
15+
return;
16+
}
17+
18+
if (arr[i] == key) {
19+
System.out.print(i + " ");
20+
}
21+
22+
printAll(arr, key, i + 1);
23+
}
24+
25+
public static void main(String[] args) {
26+
int[] arr = {3, 2, 4, 5, 6, 2, 7, 2, 2};
27+
printAll(arr, 2, 0);
28+
}
29+
}

0 commit comments

Comments
 (0)