Skip to content

Commit

Permalink
K-Diff Pairs and Pascal Triangle II
Browse files Browse the repository at this point in the history
  • Loading branch information
rusty-sj committed Sep 11, 2020
1 parent af29fe3 commit d05f5a5
Show file tree
Hide file tree
Showing 2 changed files with 68 additions and 0 deletions.
38 changes: 38 additions & 0 deletions KDiffPairs_LC532.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import java.util.HashSet;
import java.util.Set;

/**
* Go through numbers, when a number is not seen before, add it to set (this way we will avoid duplicate pairs in future)
* Check if number +k -k exist in set, if yes, update count. Handle k = 0 separately. Since for k = 0, we can have pair like 5, 5
* We use another hashset to store duplicate seen. duplicate pair will be counted only once hence use another set
*
* Time Complexity O(N) N: size of nums
* Space Complexity: O(N + N) worst case, all numbers will be stored in both sets
*/
public class KDiffPairs_LC532 {
public int findPairs(int[] nums, int k) {
int count = 0; // Output variable

if (nums == null || nums.length == 0 || k < 0) // Edge inputs
return count;

Set<Integer> set = new HashSet<>();
Set<Integer> duplicates = new HashSet<>();

for (int num : nums) {
if (!set.contains(num)) { // If number is not seen before
set.add(num); // Add it to set
if (k == 0) // When k is 0, don't check for further conditions
continue;
if (set.contains(num - k)) // Pair found
count += 1;
if (set.contains(num + k)) // Pair found
count += 1;
} else if (k == 0 && !duplicates.contains(num)) { // When k is 0, i & j can be same numbers
duplicates.add(num); // Add number to duplicates set when seen twice
count += 1; // Same number allowed only once, so use duplicate set
}
}
return count;
}
}
30 changes: 30 additions & 0 deletions PascalTriangleII_LC119.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import java.util.ArrayList;
import java.util.List;

public class PascalTriangleII_LC119 {

/**
* First pascal row is always [1]. Keep it hardcoded. Loop for 1 to rowIndex, use row's prev elements to find
* intermediate elements in current row. Add 1 in the end for a row
*
* Time Complexity O(N^2) where n is number of rows
* Space Complexity: O(N) only one list of size n is used
*
*/
public List<Integer> getRow(int rowIndex) {
List<Integer> row = new ArrayList<>(); // output row

if (rowIndex < 0) // Handle invalid input
return row;

row.add(1); // First element is always 1

for (int i = 1; i < rowIndex + 1; i++) { // Calculate each row upto rowIndex
for (int j = i - 1; j > 0; j--) { // Middle elements computation using row's prev values
row.set(j, row.get(j - 1) + row.get(j));
}
row.add(1); // Add last element 1
}
return row;
}
}

0 comments on commit d05f5a5

Please sign in to comment.