diff --git a/KDiffPairs.java b/KDiffPairs.java new file mode 100644 index 00000000..df875092 --- /dev/null +++ b/KDiffPairs.java @@ -0,0 +1,43 @@ +// Time Complexity : O(n) + O(n) ~ O(n) where n is the number of elements +// Space Complexity : O(n) +// Did this code successfully run on Leetcode : Yes +// Any problem you faced while coding this : Yes, was not able to come up with the solution in the mock interview + + +// Your code here along with comments explaining your approach +/* +I first counted the number of all the occurences of the numbers. The reason why I counted first is because the 2nd number might be encounter later than the first. +The formula nums[i] - nums[j] == k is equivalent to nums[j] = nums[i] - k. So if k > 0, we will find the nums[i] - k in the hashmap, if we find it which means the pair satisfies the condition and increment the count. +One thing to note is that if k == 0, then if the number of occurences is greater than 2, it means we found a pair and increment the count. +*/ + +import java.util.HashMap; +import java.util.Map; + +public class KDiffPairs { + public int findPairs(int[] nums, int k) { + HashMap hmap = new HashMap<>(); + int res = 0; + + for(int num : nums) { + hmap.put(num, hmap.getOrDefault(num, 0) + 1); + } + + for(Map.Entry entry : hmap.entrySet()) { + int key = entry.getKey(); + int val = entry.getValue(); + + if(k == 0) { + if(val > 1) { + res++; + } + } else { + if(hmap.containsKey(key + k)) { + res++; + } + } + } + + return res; + } +} diff --git a/PascalTriange.java b/PascalTriange.java new file mode 100644 index 00000000..0110f549 --- /dev/null +++ b/PascalTriange.java @@ -0,0 +1,37 @@ +// Time Complexity : O(n^2) where n is the numRows +// Space Complexity : O(n) +// Did this code successfully run on Leetcode : Yes +// Any problem you faced while coding this : No + + +// Your code here along with comments explaining your approach +/* +I first stored the initial array of [[1]] in the result. +I then started from row = 1 and then used the formula res[i-1][j-1] + res[i-1][j] to calculate the remaining columns. +*/ + + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +public class PascalTriange { + public List> generate(int numRows) { + List> res = new ArrayList<>(); + res.add(new ArrayList<>(Arrays.asList(1))); + + for(int i = 1;i temp = new ArrayList<>(); + for(int j = 0;j<=i;j++){ + if(j == 0 || j == i) { + temp.add(1); + } else { + temp.add(res.get(i-1).get(j-1) + res.get(i-1).get(j)); + } + } + res.add(temp); + } + + return res; + } +}