Skip to content

Commit

Permalink
Hashing
Browse files Browse the repository at this point in the history
  • Loading branch information
Parv-gugnani committed Jun 24, 2024
1 parent 9d6d26f commit 3be1f17
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
public class Solution {
public int solve(int[] A) {
HashMap<Long, Integer> sumMap = new HashMap<>();
long cumSum =0;
int maxLength =0;

for (int i = 0; i < A.length; i++) {
cumSum += A[i];

if(cumSum == 0){
maxLength = i + 1;
} else if(sumMap.containsKey(cumSum)){
int length = i - sumMap.get(cumSum);
maxLength = Math.max(maxLength, length);
} else {
sumMap.put(cumSum, i);
}
}

return maxLength;
}
}
16 changes: 16 additions & 0 deletions Classes/module 6/12 - hasing3/Quesiton/shaggy/Solution.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
public class Solution {
public int solve(int[] A) {
HashMap<Integer, Integer> lastIndexMap = new HashMap<>();
int minDistance = Integer.MAX_VALUE;

for (int i = 0; i < A.length; i++) {
if (lastIndexMap.containsKey(A[i])) {
int distance = i - lastIndexMap.get(A[i]);
minDistance = Math.min(minDistance, distance);
}
lastIndexMap.put(A[i], i);
}

return minDistance == Integer.MAX_VALUE ? -1 : minDistance;
}
}

0 comments on commit 3be1f17

Please sign in to comment.