diff --git a/K-diffPairsinanArray.java b/K-diffPairsinanArray.java new file mode 100644 index 00000000..2ca6d581 --- /dev/null +++ b/K-diffPairsinanArray.java @@ -0,0 +1,30 @@ +// Time Complexity : O(n) +// 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 +/* +Have a map and feed all the values from the array into the map along with their occurences. Now, iterate the +map and check if the sum of key and k already exists in the map, if so, increment the count. If k is 0, +then we need to specially check if the value is greater than 1, it means, we can get k by the difference +of those multiple occurences of that element itself, so increment the count again. + */ +class Solution { + public int findPairs(int[] nums, int k) { + Map map = new HashMap<>(); + int count = 0; + for(int num : nums) { + map.put(num, map.getOrDefault(num, 0) + 1); + } + for(Map.Entry entry : map.entrySet()) { + int key = entry.getKey(); + int val = entry.getValue(); + if(k > 0 &&map.containsKey(key + k)) + count++; + else if(k == 0 && val > 1) + count++; + } + return count; + } +} \ No newline at end of file diff --git a/PascalsTriangle.java b/PascalsTriangle.java new file mode 100644 index 00000000..d94f61d5 --- /dev/null +++ b/PascalsTriangle.java @@ -0,0 +1,33 @@ +// Time Complexity : O(n^2) +// Space Complexity : O(n^2) +// 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 +/* +The idea is to append two 1's by default(except for 0th index) to the resultant sublist and compute the +middle elements by retrieving previous iteration's generated list and add the consecutive elements from +indices 1 to i - 1 where i needs to iterate for given numRows value. As we compute this sum, append it to +the subList and add it to the resultant list. + */ +class Solution { + public List> generate(int numRows) { + List> result = new ArrayList<>(); + for(int i = 0 ; i < numRows ; i++) { + List pascalList = new ArrayList<>(); + pascalList.add(1); + if(i == 0) { + result.add(pascalList); + continue; + } + for(int j = 1 ; j <= i - 1 ; j++) { + List prevList = result.get(i - 1); + int sum = prevList.get(j - 1) + prevList.get(j); + pascalList.add(sum); + } + pascalList.add(1); + result.add(pascalList); + } + return result; + } +} \ No newline at end of file