diff --git a/KDiffPairs.java b/KDiffPairs.java new file mode 100644 index 00000000..fecaf4f2 --- /dev/null +++ b/KDiffPairs.java @@ -0,0 +1,38 @@ + +// 532. K-diff Pairs in an Array +// https://leetcode.com/problems/k-diff-pairs-in-an-array/description/ + +/** + * Time Complexity: O(n) since we iterate over each element + * Space Complexity: O(n) since in worst case we store all elements + */ + +class Solution { + public int findPairs(int[] nums, int k) { + Map map = new HashMap<>(); + + int count = 0; + + for(int num : nums){ // count frequency of numbers + map.put(num, map.getOrDefault(num, 0) + 1); + } + + for(int num : map.keySet()){ // iterating on keys as we want unique pairs + + int anotherNumber = num + k; + + // if k is 0, we need to check if the same number exists more than once as we cannot consider same number + if(k == 0){ + if(map.get(anotherNumber) > 1){ + count++; + } + }else{ + if(map.containsKey(anotherNumber)){ + count++; + } + } + } + + return count; + } +} \ No newline at end of file diff --git a/PascalsTriangle.java b/PascalsTriangle.java new file mode 100644 index 00000000..489b9dbf --- /dev/null +++ b/PascalsTriangle.java @@ -0,0 +1,37 @@ +// 118. Pascal's Triangle +// https://leetcode.com/problems/pascals-triangle/description/ + +/** + * Time Complexity: O(n * m) ~ O(n^2) since we iterate over each element + * Space Complexity: O(1) since no auxillary space as we dont consider result + */ + + + +class Solution { + public List> generate(int numRows) { + List> result = new ArrayList<>(); + + for(int i = 0 ; i < numRows ; i++){ + + List currList = new ArrayList<>(); + + for(int j = 0 ; j <= i ; j++){ + + if(j == 0 || j == i){ + currList.add(1); + }else{ + List prevList = result.get(i - 1); + + int currNumber = prevList.get(j - 1) + prevList.get(j); + + currList.add(currNumber); + } + } + + result.add(currList); + } + + return result; + } +} \ No newline at end of file