diff --git a/kdiffPairs.java b/kdiffPairs.java new file mode 100644 index 00000000..38bf2d0a --- /dev/null +++ b/kdiffPairs.java @@ -0,0 +1,34 @@ +// Time Complexity : O(n). +// Space Complexity : O(n) +// Did this code successfully run on Leetcode : Yes +// Approach : Maintaining a HashMap with frequencies and iterating over the hashmap to find the complement helps in finding the k diff +// pairs as only unique values are allowed. Only special case is for k=0, for which we need to consider the keys that have more than 2 as their frequency. + +class Solution { + public int findPairs(int[] nums, int k) { + HashMap map = new HashMap<>(); + int count = 0; + for(int num : nums){ //store in hashmap + if(map.containsKey(num)){ + map.put(num, map.get(num)+1); + } else{ + map.put(num, 1); + } + } + + + for(int num : map.keySet()){ + if(k>0){ //search for complement in hashmap + if(map.containsKey(num - k)){ + count++; + } + } + else if(k==0){ //checking frequencies for k=0 and we need same key pairs + if(map.get(num) >= 2){ + count++; + } + } + } + return count; + } +} \ No newline at end of file diff --git a/pascalTriangle.java b/pascalTriangle.java new file mode 100644 index 00000000..5fb7bd2a --- /dev/null +++ b/pascalTriangle.java @@ -0,0 +1,27 @@ +// Time Complexity : O(n). +// Space Complexity : O(n) +// Did this code successfully run on Leetcode : Yes +// Approach : We can construct a row from previous row by adding index and index-1 of previous row for a index in current row. +// And append 1 at both the ends of the row. As the output is expected in List>, we perform operations on the List. + + +class Solution { + public List> generate(int numRows) { + List> result = new ArrayList<>(); + if(numRows >= 1){ + result.add(new ArrayList<>(Arrays.asList(1))); // first row is always [1] + } + for(int i=1;i curr = new ArrayList<>(); + List prev = new ArrayList<>(); + prev = result.get(i-1); + curr.add(1); //first elements is always 1 + for(int j=1;j