Created
April 13, 2022 17:59
-
-
Save ravichandrae/ab9c1827d94a834fed3f8be1899101f8 to your computer and use it in GitHub Desktop.
Finding the length of the longest subarray with unique/distinct numbers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.HashMap; | |
import java.util.Map; | |
public class LongestSubarrayUnique { | |
public static void main(String[] args) { | |
System.out.println(longestDistinctSubarray(null)); //Expected 0 | |
System.out.println(longestDistinctSubarray(new int[]{})); //Expected 0 | |
System.out.println(longestDistinctSubarray(new int[]{1})); //Expected 1 | |
System.out.println(longestDistinctSubarray(new int[]{1, 2, 3, 4, 5})); //Expected 5 | |
System.out.println(longestDistinctSubarray(new int[]{23, 9, 36, 23, 4})); //Expected 4 | |
System.out.println(longestDistinctSubarray(new int[]{6, 6, 6, 6})); //Expected 1 | |
System.out.println(longestDistinctSubarray(new int[]{10, 10, 20, 10, 30, 10})); //Expected 3 | |
System.out.println(longestDistinctSubarray(new int[]{10, 10, 20, 10, 30, 50})); //Expected 4 | |
System.out.println(longestDistinctSubarray(new int[]{5, 10, 20, 30, 10})); //Expected 4 | |
} | |
private static int longestDistinctSubarray(int[] arr) { | |
int result = 0; | |
if (arr == null || arr.length == 0) { | |
return result; | |
} | |
int begin, end; | |
Map<Integer, Integer> elementIndexMap = new HashMap<>(); | |
for (begin = 0, end = 0; end < arr.length; end++) { | |
if (elementIndexMap.containsKey(arr[end])) { | |
result = Math.max(result, end - begin); | |
int dupIndex = elementIndexMap.get(arr[end]); | |
while (begin <= dupIndex) { | |
elementIndexMap.remove(arr[begin]); | |
begin++; | |
} | |
} | |
elementIndexMap.put(arr[end], end); | |
} | |
result = Math.max(result, end - begin); | |
return result; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment