diff --git a/KDiffPairsInAnArray.java b/KDiffPairsInAnArray.java new file mode 100644 index 00000000..defe88a5 --- /dev/null +++ b/KDiffPairsInAnArray.java @@ -0,0 +1,37 @@ +import java.util.HashMap; +import java.util.Map; + +/** + * I took frequencyMap to maintain the count of occurences of a num in nums. + * I iterated on the frequencyMap to avoid finding repeated pairs. + * Considering the key as nums[i], I am looking for nums[j] which is equal to nums[i] - k. + * nums[j] can also be equal to nums[i] + k. But I'm not looking for it to avoid finding repeated pairs. + * When nums[i] - k is found I am increasing the result by 1. + * When k = 0, I need look for repeated numbers since nums[i] - nums[j] = 0 => nums[i] = nums[j]. + */ +// Time: N + N ~= O(N) +// Space: O(N) for frequencyMap +class Solution { + public int findPairs(int[] nums, int k) { + Map frequencyMap = new HashMap<>(); + // Populate map + for (int num: nums) { + frequencyMap.put(num, frequencyMap.getOrDefault(num, 0) + 1); + } + int numOfPairs = 0; + // Iterate through key set of the map + for (Map.Entry entry: frequencyMap.entrySet()) { + if (k != 0) { + if (frequencyMap.containsKey(entry.getKey() - k)) { + numOfPairs ++; + } + } else { + // As k = 0, look for repeated number + if (entry.getValue() >= 2) { + numOfPairs ++; + } + } + } + return numOfPairs; + } +} \ No newline at end of file diff --git a/PascalsTriangle.java b/PascalsTriangle.java new file mode 100644 index 00000000..08efe0d6 --- /dev/null +++ b/PascalsTriangle.java @@ -0,0 +1,33 @@ +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +/** + * I initalized the first row and second row. + * Iterated through each index of the next rows. Initialized values first and last indices of each row as 1. + * Calculated the remaining values using the formula triangle.get(rowNum - 1).get(index - 1) + triangle.get(rowNum - 1).get(index) + */ +// Time: O(N * (N + 1) / 2) ~= O(N^2); where N = numRows +// Space: O(N) for currentRow inside for loop +class Solution { + public List> generate(int numRows) { + List> triangle = new ArrayList<>(); + triangle.add(Arrays.asList(1)); // first row + if (numRows == 1) { + return triangle; + } + triangle.add(Arrays.asList(1, 1)); // second row + // Iterate from third row to the end + for (int rowNum = 2; rowNum < numRows; rowNum ++) { + List currentRow = new ArrayList<>(); + currentRow.add(1); // first element + for (int index = 1; index < rowNum; index ++) { + currentRow.add(index, + triangle.get(rowNum - 1).get(index - 1) + triangle.get(rowNum - 1).get(index)); + } + currentRow.add(1); // last element + triangle.add(currentRow); + } + return triangle; + } +} \ No newline at end of file