Skip to content

Commit 2884730

Browse files
committed
Add Prefix Sum and Hash Map / Set problems with solution
1 parent 696ce9d commit 2884730

11 files changed

+340
-19
lines changed

README.md

+29-19
Original file line numberDiff line numberDiff line change
@@ -63,25 +63,35 @@ leetcode-75-solutions-java/
6363

6464
## Problems and Solutions
6565

66-
| Category | Problem | Solution | Difficulty |
67-
|----------------|---------------------------------------------------------------------------------------------------------------------|---------------------------------------------------------------------------------------------|------------|
68-
| Array / String | [Merge Strings Alternately](https://leetcode.com/problems/merge-strings-alternately/) | [MergeStringsAlternately.java](src/array_string/MergeStringsAlternately.java) | Easy |
69-
| Array / String | [Greatest Common Divisor of Strings](https://leetcode.com/problems/greatest-common-divisor-of-strings/) | [GreatestCommonDivisorOfStrings.java](src/array_string/GreatestCommonDivisorOfStrings.java) | Easy |
70-
| Array / String | [Kids With the Greatest Number of Candies](https://leetcode.com/problems/kids-with-the-greatest-number-of-candies/) | [GreatestNumberOfCandies.java](src/array_string/GreatestNumberOfCandies.java) | Easy |
71-
| Array / String | [Can Place Flowers](https://leetcode.com/problems/can-place-flowers/) | [CanPlaceFlowers.java](src/array_string/CanPlaceFlowers.java) | Easy |
72-
| Array / String | [Reverse Vowels of a String](https://leetcode.com/problems/reverse-vowels-of-a-string/) | [ReverseVowelsOfString.java](src/array_string/ReverseVowelsOfString.java) | Easy |
73-
| Array / String | [Reverse Words in a String](https://leetcode.com/problems/reverse-words-in-a-string/) | [ReverseWordsInString.java](src/array_string/ReverseWordsInString.java) | Medium |
74-
| Array / String | [Product of Array Except Self](https://leetcode.com/problems/product-of-array-except-self/) | [ProductExceptSelf.java](src/array_string/ProductExceptSelf.java) | Medium |
75-
| Array / String | [Increasing Triplet Subsequence](https://leetcode.com/problems/increasing-triplet-subsequence/) | [IncreasingTriplet.java](src/array_string/IncreasingTriplet.java) | Medium |
76-
| Array / String | [String Compression](https://leetcode.com/problems/string-compression/) | [StringCompressor.java](src/array_string/StringCompressor.java) | Medium |
77-
| Two Pointers | [Move Zeroes](https://leetcode.com/problems/move-zeroes/) | [ZeroMover.java](src/two_pointers/ZeroMover.java) | Easy |
78-
| Two Pointers | [Is Subsequence](https://leetcode.com/problems/is-subsequence/) | [SubsequenceChecker.java](src/two_pointers/SubsequenceChecker.java) | Easy |
79-
| Two Pointers | [Container With Most Water](https://leetcode.com/problems/container-with-most-water/) | [WaterContainer.java](src/two_pointers/WaterContainer.java) | Medium |
80-
| Two Pointers | [Max Number of K-Sum Pairs](https://leetcode.com/problems/max-number-of-k-sum-pairs/) | [MaxOperationsCounter.java](src/two_pointers/MaxOperationsCounter.java) | Medium |
81-
| ... | ... | ... | ... |
82-
| Trie | [Implement Trie (Prefix Tree)](https://leetcode.com/problems/implement-trie-prefix-tree) | [PrefixTrie.java](src/trie/PrefixTrie.java) | Medium |
83-
| Trie | [Search Suggestions System](https://leetcode.com/problems/search-suggestions-system) | [SearchSuggestionsSystem.java](src/trie/SearchSuggestionsSystem.java) | Medium |
84-
| ... | ... | ... | ... |
66+
| Category | Problem | Solution | Difficulty |
67+
|----------------|---------------------------------------------------------------------------------------------------------------------------------------------------|---------------------------------------------------------------------------------------------|------------|
68+
| Array / String | [Merge Strings Alternately](https://leetcode.com/problems/merge-strings-alternately/) | [MergeStringsAlternately.java](src/array_string/MergeStringsAlternately.java) | Easy |
69+
| Array / String | [Greatest Common Divisor of Strings](https://leetcode.com/problems/greatest-common-divisor-of-strings/) | [GreatestCommonDivisorOfStrings.java](src/array_string/GreatestCommonDivisorOfStrings.java) | Easy |
70+
| Array / String | [Kids With the Greatest Number of Candies](https://leetcode.com/problems/kids-with-the-greatest-number-of-candies/) | [GreatestNumberOfCandies.java](src/array_string/GreatestNumberOfCandies.java) | Easy |
71+
| Array / String | [Can Place Flowers](https://leetcode.com/problems/can-place-flowers/) | [CanPlaceFlowers.java](src/array_string/CanPlaceFlowers.java) | Easy |
72+
| Array / String | [Reverse Vowels of a String](https://leetcode.com/problems/reverse-vowels-of-a-string/) | [ReverseVowelsOfString.java](src/array_string/ReverseVowelsOfString.java) | Easy |
73+
| Array / String | [Reverse Words in a String](https://leetcode.com/problems/reverse-words-in-a-string/) | [ReverseWordsInString.java](src/array_string/ReverseWordsInString.java) | Medium |
74+
| Array / String | [Product of Array Except Self](https://leetcode.com/problems/product-of-array-except-self/) | [ProductExceptSelf.java](src/array_string/ProductExceptSelf.java) | Medium |
75+
| Array / String | [Increasing Triplet Subsequence](https://leetcode.com/problems/increasing-triplet-subsequence/) | [IncreasingTriplet.java](src/array_string/IncreasingTriplet.java) | Medium |
76+
| Array / String | [String Compression](https://leetcode.com/problems/string-compression/) | [StringCompressor.java](src/array_string/StringCompressor.java) | Medium |
77+
| Two Pointers | [Move Zeroes](https://leetcode.com/problems/move-zeroes/) | [ZeroMover.java](src/two_pointers/ZeroMover.java) | Easy |
78+
| Two Pointers | [Is Subsequence](https://leetcode.com/problems/is-subsequence/) | [SubsequenceChecker.java](src/two_pointers/SubsequenceChecker.java) | Easy |
79+
| Two Pointers | [Container With Most Water](https://leetcode.com/problems/container-with-most-water/) | [WaterContainer.java](src/two_pointers/WaterContainer.java) | Medium |
80+
| Two Pointers | [Max Number of K-Sum Pairs](https://leetcode.com/problems/max-number-of-k-sum-pairs/) | [MaxOperationsCounter.java](src/two_pointers/MaxOperationsCounter.java) | Medium |
81+
| Sliding Window | [Maximum Average Subarray I](https://leetcode.com/problems/maximum-average-subarray-i/) | [MaxAverageSubarrayCalculator.java](src/sliding_window/MaxAverageSubarrayCalculator.java) | Easy |
82+
| Sliding Window | [Maximum Number of Vowels in a Substring of Given Length](https://leetcode.com/problems/maximum-number-of-vowels-in-a-substring-of-given-length/) | [MaxVowelSubstringCalculator.java](src/sliding_window/MaxVowelSubstringCalculator.java) | Medium |
83+
| Sliding Window | [Max Consecutive Ones III](https://leetcode.com/problems/max-consecutive-ones-iii/) | [BinaryArrayMaxOnesCalculator.java](src/sliding_window/BinaryArrayMaxOnesCalculator.java) | Medium |
84+
| Sliding Window | [Longest Subarray of 1's After Deleting One Element](https://leetcode.com/problems/longest-subarray-of-1s-after-deleting-one-element/) | [BinarySubarrayCalculator.java](src/sliding_window/BinarySubarrayCalculator.java) | Medium |
85+
| Prefix Sum | [Find the Highest Altitude](https://leetcode.com/problems/find-the-highest-altitude/) | [AltitudeCalculator.java](src/prefix_sum/AltitudeCalculator.java) | Easy |
86+
| Prefix Sum | [Find Pivot Index](https://leetcode.com/problems/find-pivot-index/) | [PivotFinder.java](src/prefix_sum/PivotFinder.java) | Easy |
87+
| Hash Map / Set | [Find the Difference of Two Arrays](https://leetcode.com/problems/find-the-difference-of-two-arrays/) | [ArraysDifferenceFinder.java](src/hash_map_set/ArraysDifferenceFinder.java) | Easy |
88+
| Hash Map / Set | [Unique Number of Occurrences](https://leetcode.com/problems/unique-number-of-occurrences/) | [UniqueOccurrenceChecker.java](src/hash_map_set/UniqueOccurrenceChecker.java) | Easy |
89+
| Hash Map / Set | [Determine if Two Strings Are Close](https://leetcode.com/problems/determine-if-two-strings-are-close/) | [StringCloseChecker.java](src/hash_map_set/StringCloseChecker.java) | Medium |
90+
| Hash Map / Set | [Equal Row and Column Pairs](https://leetcode.com/problems/equal-row-and-column-pairs/) | [MatrixPairs.java](src/hash_map_set/MatrixPairs.java) | Medium |
91+
| ... | ... | ... | ... |
92+
| Trie | [Implement Trie (Prefix Tree)](https://leetcode.com/problems/implement-trie-prefix-tree) | [PrefixTrie.java](src/trie/PrefixTrie.java) | Medium |
93+
| Trie | [Search Suggestions System](https://leetcode.com/problems/search-suggestions-system) | [SearchSuggestionsSystem.java](src/trie/SearchSuggestionsSystem.java) | Medium |
94+
| ... | ... | ... | ... |
8595

8696
## Usage
8797

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
package hash_map_set;
2+
3+
import java.util.*;
4+
import java.util.stream.Collectors;
5+
6+
public class ArraysDifferenceFinder {
7+
8+
public List<List<Integer>> findDifference(int[] nums1, int[] nums2) {
9+
Set<Integer> set1 = new HashSet<>(Arrays.stream(nums1).boxed().collect(Collectors.toSet())); // convert nums1 to set
10+
Set<Integer> set2 = new HashSet<>(Arrays.stream(nums2).boxed().collect(Collectors.toSet())); // convert nums2 to set
11+
12+
List<Integer> diff1 = set1.stream().filter(num -> !set2.contains(num)).collect(Collectors.toList()); // nums1 diff nums2
13+
List<Integer> diff2 = set2.stream().filter(num -> !set1.contains(num)).collect(Collectors.toList()); // nums2 diff nums1
14+
15+
return Arrays.asList(diff1, diff2);
16+
}
17+
18+
public static void main(String[] args) {
19+
20+
ArraysDifferenceFinder finder = new ArraysDifferenceFinder();
21+
22+
List<List<Integer>> result1 = finder.findDifference(new int[] {1,2,3}, new int[] {2,4,6});
23+
assert result1.get(0).equals(Arrays.asList(1,3)) && result1.get(1).equals(Arrays.asList(4,6)) : "Test case 1 failed";
24+
25+
List<List<Integer>> result2 = finder.findDifference(new int[] {1,2,3,3}, new int[] {1,1,2,2});
26+
assert result2.get(0).equals(Arrays.asList(3)) && result2.get(1).isEmpty() : "Test case 2 failed";
27+
28+
System.out.println("All test cases passed!");
29+
}
30+
}

src/hash_map_set/MatrixPairs.java

+40
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
package hash_map_set;
2+
3+
import java.util.HashMap;
4+
import java.util.Map;
5+
import java.util.Arrays;
6+
7+
public class MatrixPairs {
8+
9+
public int countEqualPairs(int[][] matrix) {
10+
Map<String, Integer> rowRepresentationCount = new HashMap<>();
11+
12+
for (int[] row : matrix) {
13+
String rowString = Arrays.toString(row);
14+
rowRepresentationCount.put(rowString, rowRepresentationCount.getOrDefault(rowString, 0) + 1);
15+
}
16+
17+
int equalPairCount = 0;
18+
int matrixSize = matrix.length;
19+
20+
for (int colIndex = 0; colIndex < matrixSize; colIndex++) {
21+
int[] column = new int[matrixSize];
22+
for (int rowIndex = 0; rowIndex < matrixSize; rowIndex++) {
23+
column[rowIndex] = matrix[rowIndex][colIndex];
24+
}
25+
String colString = Arrays.toString(column);
26+
equalPairCount += rowRepresentationCount.getOrDefault(colString, 0);
27+
}
28+
29+
return equalPairCount;
30+
}
31+
32+
public static void main(String[] args) {
33+
MatrixPairs checker = new MatrixPairs();
34+
35+
assert checker.countEqualPairs(new int[][]{{3,2,1},{1,7,6},{2,7,7}}) == 1 : "Test case 1 failed";
36+
assert checker.countEqualPairs(new int[][]{{3,1,2,2},{1,4,4,5},{2,4,2,2},{2,4,2,2}}) == 3 : "Test case 2 failed";
37+
38+
System.out.println("All test cases passed!");
39+
}
40+
}
+42
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
package hash_map_set;
2+
3+
import java.util.Arrays;
4+
5+
public class StringCloseChecker {
6+
7+
private static final int LETTER_COUNT = 26;
8+
9+
public boolean areStringsClose(String str1, String str2) {
10+
int[] freq1 = new int[LETTER_COUNT];
11+
int[] freq2 = new int[LETTER_COUNT];
12+
13+
for (char ch : str1.toCharArray()) {
14+
freq1[ch - 'a']++;
15+
}
16+
17+
for (char ch : str2.toCharArray()) {
18+
freq2[ch - 'a']++;
19+
}
20+
21+
for (int i = 0; i < LETTER_COUNT; i++) {
22+
if (freq1[i] == 0 && freq2[i] != 0 || freq1[i] != 0 && freq2[i] == 0) {
23+
return false;
24+
}
25+
}
26+
27+
Arrays.sort(freq1);
28+
Arrays.sort(freq2);
29+
30+
return Arrays.equals(freq1, freq2);
31+
}
32+
33+
public static void main(String[] args) {
34+
StringCloseChecker checker = new StringCloseChecker();
35+
36+
assert checker.areStringsClose("abc", "bca") : "Test case 1 failed";
37+
assert !checker.areStringsClose("a", "aa") : "Test case 2 failed";
38+
assert checker.areStringsClose("cabbba", "abbccc") : "Test case 3 failed";
39+
40+
System.out.println("All test cases passed!");
41+
}
42+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
package hash_map_set;
2+
3+
import java.util.*;
4+
5+
public class UniqueOccurrenceChecker {
6+
7+
public boolean hasUniqueOccurrences(int[] numbers) {
8+
Map<Integer, Integer> numberCounts = new HashMap<>();
9+
for (int num : numbers) {
10+
numberCounts.put(num, numberCounts.getOrDefault(num, 0) + 1);
11+
}
12+
13+
Set<Integer> uniqueCounts = new HashSet<>(numberCounts.values());
14+
return numberCounts.size() == uniqueCounts.size();
15+
}
16+
17+
public static void main(String[] args) {
18+
UniqueOccurrenceChecker checker = new UniqueOccurrenceChecker();
19+
20+
assert checker.hasUniqueOccurrences(new int[]{1,2,2,1,1,3}) : "Test case 1 failed";
21+
assert !checker.hasUniqueOccurrences(new int[]{1,2}) : "Test case 2 failed";
22+
assert checker.hasUniqueOccurrences(new int[]{-3,0,1,-3,1,1,1,-3,10,0}) : "Test case 3 failed";
23+
24+
System.out.println("All test cases passed!");
25+
}
26+
}
+26
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
package prefix_sum;
2+
3+
public class AltitudeCalculator {
4+
5+
public int largestAltitude(int[] gain) {
6+
int currentAltitude = 0;
7+
int maxAltitude = 0;
8+
9+
for (int altitudeChange : gain) {
10+
currentAltitude += altitudeChange;
11+
maxAltitude = Math.max(maxAltitude, currentAltitude);
12+
}
13+
14+
return maxAltitude;
15+
}
16+
17+
public static void main(String[] args) {
18+
19+
AltitudeCalculator calculator = new AltitudeCalculator();
20+
21+
assert calculator.largestAltitude(new int[]{-5, 1, 5, 0, -7}) == 1 : "Test case 1 failed";
22+
assert calculator.largestAltitude(new int[]{-4, -3, -2, -1, 4, 3, 2}) == 0 : "Test case 2 failed";
23+
24+
System.out.println("All test cases passed!");
25+
}
26+
}

src/prefix_sum/PivotFinder.java

+31
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
package prefix_sum;
2+
3+
import java.util.Arrays;
4+
5+
public class PivotFinder {
6+
7+
public int pivotIndex(int[] nums) {
8+
int total = Arrays.stream(nums).sum();
9+
int leftSum = 0;
10+
11+
for (int i = 0; i < nums.length; i++) {
12+
if (leftSum == total - leftSum - nums[i]) {
13+
return i;
14+
}
15+
leftSum += nums[i];
16+
}
17+
18+
return -1;
19+
}
20+
21+
public static void main(String[] args) {
22+
23+
PivotFinder finder = new PivotFinder();
24+
25+
assert finder.pivotIndex(new int[]{1,7,3,6,5,6}) == 3 : "Test case 1 failed";
26+
assert finder.pivotIndex(new int[]{1,2,3}) == -1 : "Test case 2 failed";
27+
assert finder.pivotIndex(new int[]{2,1,-1}) == 0 : "Test case 3 failed";
28+
29+
System.out.println("All test cases passed!");
30+
}
31+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
package sliding_window;
2+
3+
public class BinaryArrayMaxOnesCalculator {
4+
5+
public int longestOnes(int[] nums, int flipsAllowed) {
6+
int left = 0, right;
7+
for (right = 0; right < nums.length; ++right) {
8+
if (nums[right] == 0) flipsAllowed--;
9+
if (flipsAllowed < 0 && nums[left++] == 0) flipsAllowed++;
10+
}
11+
return right - left;
12+
}
13+
14+
public static void main(String[] args) {
15+
16+
BinaryArrayMaxOnesCalculator calculator = new BinaryArrayMaxOnesCalculator();
17+
18+
assert calculator.longestOnes(new int[]{1,1,1,0,0,0,1,1,1,1,0}, 2) == 6 : "Test case 1 failed";
19+
assert calculator.longestOnes(new int[]{0,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,1}, 3) == 10 : "Test case 2 failed";
20+
21+
System.out.println("All test cases passed!");
22+
}
23+
}

0 commit comments

Comments
 (0)