878670. Print GeeksForGeeks
Basic
Print GeeksForGeeks
Summary
Print all the geeks present in the array where index is smaller than the value at that index. The idea is to traverse through the array and whenever we find a geek, print it. A geek is defined as an element at index i such that arr[i] <= i.
Detailed Explanation
We can solve this problem by iterating over the array and printing the elements whose index is less than or equal to their value. Here's the step-by-step breakdown of the solution:
- Initialize a variable
ito 0, which will be used as the index. - Iterate through the array until
iis within the bounds of the array. - For each iteration, check if the value at index
i(i.e.,arr[i]) is less than or equal toi. If it is, print the element at that index (arr[i]). - Increment
iby 1 and repeat steps 2-3 until the end of the array. - Since we only print elements where the index is less than or equal to their value, these are the geeks in the array.
Time complexity: O(n), where n is the length of the array. Space complexity: O(1), as we're not using any additional space that scales with the input size.
Optimized Solutions
Java
public void printGeeks(int[] arr) {
for (int i = 0; i < arr.length; i++) {
if (arr[i] <= i) {
System.out.println(arr[i]);
}
}
}