Skip to content

Commit

Permalink
Merge branch 'neetcode-gh:main' into main
Browse files Browse the repository at this point in the history
  • Loading branch information
miladra authored Jul 11, 2022
2 parents da25527 + 8847d2c commit 057f985
Show file tree
Hide file tree
Showing 369 changed files with 8,338 additions and 275 deletions.
28 changes: 13 additions & 15 deletions 125-Valid-Palindrome.py
Original file line number Diff line number Diff line change
@@ -1,19 +1,17 @@
class Solution:
def isPalindrome(self, s: str) -> bool:
l, r = 0, len(s) - 1
while l < r:
while l < r and not self.alphanum(s[l]):
l += 1
while l < r and not self.alphanum(s[r]):
r -= 1
if s[l].lower() != s[r].lower():
l = 0
r = len(s)-1
while l<r:
if s[l].lower()==s[r].lower():
l+=1
r-=1
continue

elif not (65<=ord(s[l])<=90 or 97<=ord(s[l])<=122 or 48<=ord(s[l])<=57):
l+=1
elif not (65<=ord(s[r])<=90 or 97<=ord(s[r])<=122 or 48<=ord(s[r])<=57):
r-=1
else:
return False
l += 1
r -= 1
return True

# Could write own alpha-numeric function
def alphanum(self, c):
return (ord('A') <= ord(c) <= ord('Z') or
ord('a') <= ord(c) <= ord('z') or
ord('0') <= ord(c) <= ord('9'))
2 changes: 1 addition & 1 deletion 261-Graph-Valid-Tree.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# Problem is free on Lintcode
# Problem is free on Lintcode https://www.lintcode.com/problem/178/
class Solution:
"""
@param n: An integer
Expand Down
10 changes: 0 additions & 10 deletions 371-Sum-of-Two-Integers.java

This file was deleted.

2 changes: 1 addition & 1 deletion 416-Partition-Equal-Subset-Sum.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,4 +15,4 @@ def canPartition(self, nums: List[int]) -> bool:
nextDP.add(t + nums[i])
nextDP.add(t)
dp = nextDP
return True if target in dp else False
return False
31 changes: 31 additions & 0 deletions 43-Number_of_Connected_Components_in_an_Undirected_Graph.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@

class Solution:
def count_components(self, n: int, edges: List[List[int]]) -> int:
parent = [i for i in range(n)]
rank = [1] * n

def find_union(node: int) -> None:
result = node
while result != parent[result]:
parent[result] = parent[parent[result]] # path compression
result = parent[result]
return result

def union(node_1: int, node_2: int):
parent_1 = find_union(node_1)
parent_2 = find_union(node_2)
if parent_1 == parent_2:
return 0
if rank[parent_2] < rank[parent_1]:
parent[parent_1] = parent_2
rank[parent_2] += rank[parent_1]
else:
parent[parent_2] = parent_1
rank[parent_1] += rank[parent_2]
return 1

result = n
for node_1, node_2 in edges:
result -= union(node_1, node_2)
return result

11 changes: 4 additions & 7 deletions 49-Group-Anagrams.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,7 @@
class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
ans = collections.defaultdict(list)

hashmap = defaultdict(list)
for s in strs:
count = [0] * 26
for c in s:
count[ord(c) - ord('a')] += 1
ans[tuple(count)].append(s)
return ans.values()
# keys can be strings, bcz they are immutable.
hashmap[str(sorted(s))].append(s)
return hashmap.values()
File renamed without changes.
2 changes: 1 addition & 1 deletion 55-Jump-Game.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,4 @@ def canJump(self, nums: List[int]) -> bool:
for i in range(len(nums) - 2, -1, -1):
if i + nums[i] >= goal:
goal = i
return True if goal == 0 else False
return goal == 0
15 changes: 15 additions & 0 deletions csharp/1-Two-Sum.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
public class Solution {
public int[] TwoSum(int[] nums, int target) {
Dictionary<int, int> indices = new Dictionary<int, int>();

for (int i = 0; i < nums.Length; i++) {
var diff = target - nums[i];
if (indices.ContainsKey(diff)) {
return new int[] {indices[diff], i};
}
indices[nums[i]] = i;
}
return null;
}
}

13 changes: 13 additions & 0 deletions csharp/121-Best-Time-To-Buy-and-Sell-Stock.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
public class Solution {
public int MaxProfit(int[] prices) {
int maxProfit = 0;
int minPrice = prices[0];

for (int i = 1; i < prices.Length; i++) {
int currPrice = prices[i];
minPrice = Math.Min(minPrice, currPrice);
maxProfit = Math.Max(maxProfit, currPrice - minPrice);
}
return maxProfit;
}
}
21 changes: 21 additions & 0 deletions csharp/125-Valid-Palindrome.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
public class Solution {
public bool IsPalindrome(string s) {
int left = 0;
int right = s.Length - 1;

while (left < right) {
if (!char.IsLetterOrDigit(s[left])) {
left++;
} else if (!char.IsLetterOrDigit(s[right])) {
right--;
} else {
if (char.ToLower(s[left]) != char.ToLower(s[right])) {
return false;
}
left++;
right--;
}
}
return true;
}
}
28 changes: 28 additions & 0 deletions csharp/155-Min-Stack.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
public class MinStack {
private Stack<int> stack;
private Stack<int> minStack;

public MinStack() {
stack = new Stack<int>();
minStack = new Stack<int>();
}

public void Push(int val) {
stack.Push(val);
int min = Math.Min(val, minStack.Count != 0 ? minStack.Peek() : val);
minStack.Push(min);
}

public void Pop() {
stack.Pop();
minStack.Pop();
}

public int Top() {
return stack.Peek();
}

public int GetMin() {
return minStack.Peek();
}
}
20 changes: 20 additions & 0 deletions csharp/167-Two-Sum-II.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
public class Solution {
public int[] TwoSum(int[] numbers, int target) {
// Using 2 pointers. Since sorted, if l+r > target, decrease r.
// Else if l+r < target, increase l. Else, result is found.
int left = 0, right = numbers.Length - 1;

while (left < right) {
int sum = numbers[left] + numbers[right];
if (sum > target) {
right--;
} else if (sum < target) {
left++;
} else {
return new int[] {left + 1, right + 1};
}
}

return new int[0];
}
}
20 changes: 20 additions & 0 deletions csharp/20-Valid-Parentheses.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
public class Solution {
public bool IsValid(string s) {
var stack = new Stack<char>();
var pairs = new Dictionary<char, char>() {
[')'] = '(',
[']'] = '[',
['}'] = '{'
};

foreach (char c in s) {
if (!pairs.ContainsKey(c)) {
stack.Push(c);
} else if (stack.Count == 0 || stack.Pop() != pairs[c]) {
return false;
}
}

return stack.Count == 0;
}
}
11 changes: 11 additions & 0 deletions csharp/217-Contains-Duplicate.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
public class Solution {
public bool ContainsDuplicate(int[] nums) {
HashSet<int> set = new HashSet<int>();

foreach (int x in nums){
if (set.Contains(x)) return true;
set.Add(x);
}
return false;
}
}
20 changes: 20 additions & 0 deletions csharp/242-Valid-Anagram.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
public class Solution {
public bool IsAnagram(string s, string t) {
if (s.Length != t.Length) return false;
if (s == t) return true;

Dictionary<char, int> sCounts = new Dictionary<char, int>();
Dictionary<char, int> tCounts = new Dictionary<char, int>();

for (int i = 0; i < s.Length; i++) {
sCounts[s[i]] = 1 + (sCounts.ContainsKey(s[i]) ? sCounts[s[i]] : 0);
tCounts[t[i]] = 1 + (tCounts.ContainsKey(t[i]) ? tCounts[t[i]] : 0);
}

foreach (char c in sCounts.Keys) {
int tCount = tCounts.ContainsKey(c) ? tCounts[c] : 0;
if (sCounts[c] != tCount) return false;
}
return true;
}
}
19 changes: 19 additions & 0 deletions csharp/3-Longest-Substring-Without-Repeating-Characters.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
public class Solution {
public int LengthOfLongestSubstring(string s) {
int leftPointer = 0, rightPointer = 0, maxLength = 0;
HashSet<int> chars = new HashSet<int>();

while (rightPointer < s.Length) {
char currChar = s[rightPointer];
if (chars.Contains(currChar)) { // Move left pointer until all duplicate chars removed
chars.Remove(s[leftPointer]);
leftPointer++;
} else {
chars.Add(currChar);
maxLength = Math.Max(maxLength, rightPointer - leftPointer + 1);
rightPointer++;
}
}
return maxLength;
}
}
21 changes: 21 additions & 0 deletions csharp/424-Longest-Repeating-Character-Replacement.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
public class Solution {
public int CharacterReplacement(string s, int k) {
int left = 0, maxLength = 0;
int mostFrequentLetterCount = 0; // Count of most frequent letter in the window
int[] charCounts = new int[26]; // Counts per letter

for (int right = 0; right < s.Length; right++) {
charCounts[s[right] - 'A']++;
mostFrequentLetterCount = Math.Max(mostFrequentLetterCount, charCounts[s[right] - 'A']);

int lettersToChange = (right - left + 1) - mostFrequentLetterCount;
if (lettersToChange > k) { // Window is invalid, decrease char count and move left pointer
charCounts[s[left] - 'A']--;
left++;
}

maxLength = Math.Max(maxLength, (right - left + 1));
}
return maxLength;
}
}
19 changes: 19 additions & 0 deletions csharp/49-Group-Anagrams.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
public class Solution {
public IList<IList<string>> GroupAnagrams(string[] strs) {
var groups = new Dictionary<string, IList<string>>();

foreach (string s in strs) {
char[] hash = new char[26];
foreach (char c in s) {
hash[c - 'a']++;
}

string key = new string(hash);
if (!groups.ContainsKey(key)) {
groups[key] = new List<string>();
}
groups[key].Add(s);
}
return groups.Values.ToList();
}
}
17 changes: 17 additions & 0 deletions csharp/704-Binary-Search.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
public class Solution {
public int Search(int[] nums, int target) {
int left = 0, right = nums.Length - 1;

while (left <= right) {
int mid = left + ((right - left) / 2); // (left + right) / 2 can lead to overflow
if (nums[mid] > target) {
right = mid - 1;
} else if (nums[mid] < target) {
left = mid + 1;
} else { // Found the value
return mid;
}
}
return -1;
}
}
34 changes: 34 additions & 0 deletions java/128. Longest Consecutive Sequence.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
class Solution {
public int longestConsecutive(int[] nums) {
Set<Integer> set = new HashSet<>();
int max = -1;
int min = 1000000000;

// Find min and max from array & add each to set
for (int i : nums) {
set.add(i);
max = Math.max(max, i);
min = Math.min(min, i);
}

int c = 0; // count streak
int res = 0; // longest streak
for (int i = min; i <= max; ++i) {
// Check if set contains ith value; increment count & remove from set
if (set.contains(i)) {
c++;
set.remove(i);
}
else {
// If not found set count to 0
c = 0;
}
// Find longest streak at every step in case we break out from loop
res = Math.max(res, c);

// If set size is less than current longest streak break as we wont get any longer streak
if (set.size() <= res && c == 0) break;
}
return res;
}
}
File renamed without changes.
Loading

0 comments on commit 057f985

Please sign in to comment.