The task description is:
I have an array of distinct numbers from 1 to n, for example arr = [5, 3, 4, 1, 2]
Initialize a variable called order to 1, now run through the arr from left to right and look for element that matches with variable order, if found increment order and move forward. In other words we can say Initialize a variable called order to 1 so first go through array from left to right and see where 1 appears in array, then increment order to 2, then move forward in array and look for 2 , if found increment order to 3. Iterating from left to right like above is called an operation
for when arr = [5,3,4,1,2], in one pass from left to right, order changes its value from 1 to 2 when arr[3] is found and then 2 to 3 when arr[4] is found
Repeat above steps until the variable order reaches value n. Number of repetitions is called operations.
So when arr [ 5,3,4,1,2], minimum number of operations required is 3
import java.util.*;
class Main {
public static int solve(List<Integer> arr) {
int n = arr.size();
int order = 0; // Number of sorted items found
int operations = 0; // Count of full array scan
while (sortedCount < n) {
order++;
for (int i = 0; i < n; i++) {
if (arr.get(i) == order + 1) {
order++;
}
}
}
return operations;
}
public static void main(String[] args) {
System.out.println(solve(Arrays.asList(5, 3, 4, 1, 2))); // Output: 3
System.out.println(solve(Arrays.asList(3,1,4,2,5))); // Output: 2
System.out.println(solve(Arrays.asList(1,2,3,4))); // Output: 1
System.out.println(solve(Arrays.asList(2,1))); // Output: 2
}
}
My code works in time O(n^2), how can we solve this in less time complexity
operations
; I think maybe you intended the loop to be like this?int operations = 0; while (sortedCount < n) { operations++;
sortedCount
is never declaredarr = [5, 3, 4, 1, 2]
) be? And for[2,1]
(last example in code?)