❔Interview Questions
INTERVIEW QUESTION - PELOTON
int shortestSubArray(int[] arr) {
// Stores first index for each number
Map<Integer, Integer> left = new HashMap<>();
// Stores last index for each number
Map<Integer, Integer> right = new HashMap<>();
// Stores frequency of each number
Map<Integer, Integer> count = new HashMap<>();
for (int i = 0; i < arr.length; i++) {
int x = arr[i];
// If first time number is seen, store first index
if (!left.containsKey(x)) {
left.put(x, i);
}
// Store last index seen
right.put(x, i);
// Increment frequency
count.put(x, count.getOrDefault(x, 0) + 1);
}
// Find highest frequency
int degree = Collections.max(count.values());
int ans = arr.length;
for (int x : count.keySet()) {
// For numbers with max frequency
if (count.get(x) == degree) {
// Calculate subarray length
ans = Math.min(ans, right.get(x) - left.get(x) + 1);
}
}
return ans;
public static void main(String[] args) {
int[] arr = {1, 2, 1, 3, 2};
int shortestSubArrayLength = shortestSubArray(arr);
System.out.println("Length of the shortest sub-array: " + shortestSubArrayLength);
}
}Sure, here's a step-by-step visualization of the code:
Visualizer:
Last updated