Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions K-diffPairsinanArray.java
Original file line number Diff line number Diff line change
@@ -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<Integer, Integer> map = new HashMap<>();
int count = 0;
for(int num : nums) {
map.put(num, map.getOrDefault(num, 0) + 1);
}
for(Map.Entry<Integer, Integer> 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;
}
}
33 changes: 33 additions & 0 deletions PascalsTriangle.java
Original file line number Diff line number Diff line change
@@ -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<List<Integer>> generate(int numRows) {
List<List<Integer>> result = new ArrayList<>();
for(int i = 0 ; i < numRows ; i++) {
List<Integer> pascalList = new ArrayList<>();
pascalList.add(1);
if(i == 0) {
result.add(pascalList);
continue;
}
for(int j = 1 ; j <= i - 1 ; j++) {
List<Integer> 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;
}
}