Skip to content

Commit 057f985

Browse files
authored
Merge branch 'neetcode-gh:main' into main
2 parents da25527 + 8847d2c commit 057f985

File tree

369 files changed

+8338
-275
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

369 files changed

+8338
-275
lines changed

125-Valid-Palindrome.py

Lines changed: 13 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,17 @@
11
class Solution:
22
def isPalindrome(self, s: str) -> bool:
3-
l, r = 0, len(s) - 1
4-
while l < r:
5-
while l < r and not self.alphanum(s[l]):
6-
l += 1
7-
while l < r and not self.alphanum(s[r]):
8-
r -= 1
9-
if s[l].lower() != s[r].lower():
3+
l = 0
4+
r = len(s)-1
5+
while l<r:
6+
if s[l].lower()==s[r].lower():
7+
l+=1
8+
r-=1
9+
continue
10+
11+
elif not (65<=ord(s[l])<=90 or 97<=ord(s[l])<=122 or 48<=ord(s[l])<=57):
12+
l+=1
13+
elif not (65<=ord(s[r])<=90 or 97<=ord(s[r])<=122 or 48<=ord(s[r])<=57):
14+
r-=1
15+
else:
1016
return False
11-
l += 1
12-
r -= 1
1317
return True
14-
15-
# Could write own alpha-numeric function
16-
def alphanum(self, c):
17-
return (ord('A') <= ord(c) <= ord('Z') or
18-
ord('a') <= ord(c) <= ord('z') or
19-
ord('0') <= ord(c) <= ord('9'))

261-Graph-Valid-Tree.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
# Problem is free on Lintcode
1+
# Problem is free on Lintcode https://www.lintcode.com/problem/178/
22
class Solution:
33
"""
44
@param n: An integer

371-Sum-of-Two-Integers.java

Lines changed: 0 additions & 10 deletions
This file was deleted.

416-Partition-Equal-Subset-Sum.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,4 +15,4 @@ def canPartition(self, nums: List[int]) -> bool:
1515
nextDP.add(t + nums[i])
1616
nextDP.add(t)
1717
dp = nextDP
18-
return True if target in dp else False
18+
return False
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
2+
class Solution:
3+
def count_components(self, n: int, edges: List[List[int]]) -> int:
4+
parent = [i for i in range(n)]
5+
rank = [1] * n
6+
7+
def find_union(node: int) -> None:
8+
result = node
9+
while result != parent[result]:
10+
parent[result] = parent[parent[result]] # path compression
11+
result = parent[result]
12+
return result
13+
14+
def union(node_1: int, node_2: int):
15+
parent_1 = find_union(node_1)
16+
parent_2 = find_union(node_2)
17+
if parent_1 == parent_2:
18+
return 0
19+
if rank[parent_2] < rank[parent_1]:
20+
parent[parent_1] = parent_2
21+
rank[parent_2] += rank[parent_1]
22+
else:
23+
parent[parent_2] = parent_1
24+
rank[parent_1] += rank[parent_2]
25+
return 1
26+
27+
result = n
28+
for node_1, node_2 in edges:
29+
result -= union(node_1, node_2)
30+
return result
31+

49-Group-Anagrams.py

Lines changed: 4 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,7 @@
11
class Solution:
22
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
3-
ans = collections.defaultdict(list)
4-
3+
hashmap = defaultdict(list)
54
for s in strs:
6-
count = [0] * 26
7-
for c in s:
8-
count[ord(c) - ord('a')] += 1
9-
ans[tuple(count)].append(s)
10-
return ans.values()
5+
# keys can be strings, bcz they are immutable.
6+
hashmap[str(sorted(s))].append(s)
7+
return hashmap.values()
File renamed without changes.

55-Jump-Game.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,4 +5,4 @@ def canJump(self, nums: List[int]) -> bool:
55
for i in range(len(nums) - 2, -1, -1):
66
if i + nums[i] >= goal:
77
goal = i
8-
return True if goal == 0 else False
8+
return goal == 0

csharp/1-Two-Sum.cs

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
public class Solution {
2+
public int[] TwoSum(int[] nums, int target) {
3+
Dictionary<int, int> indices = new Dictionary<int, int>();
4+
5+
for (int i = 0; i < nums.Length; i++) {
6+
var diff = target - nums[i];
7+
if (indices.ContainsKey(diff)) {
8+
return new int[] {indices[diff], i};
9+
}
10+
indices[nums[i]] = i;
11+
}
12+
return null;
13+
}
14+
}
15+
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
public class Solution {
2+
public int MaxProfit(int[] prices) {
3+
int maxProfit = 0;
4+
int minPrice = prices[0];
5+
6+
for (int i = 1; i < prices.Length; i++) {
7+
int currPrice = prices[i];
8+
minPrice = Math.Min(minPrice, currPrice);
9+
maxProfit = Math.Max(maxProfit, currPrice - minPrice);
10+
}
11+
return maxProfit;
12+
}
13+
}

csharp/125-Valid-Palindrome.cs

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
public class Solution {
2+
public bool IsPalindrome(string s) {
3+
int left = 0;
4+
int right = s.Length - 1;
5+
6+
while (left < right) {
7+
if (!char.IsLetterOrDigit(s[left])) {
8+
left++;
9+
} else if (!char.IsLetterOrDigit(s[right])) {
10+
right--;
11+
} else {
12+
if (char.ToLower(s[left]) != char.ToLower(s[right])) {
13+
return false;
14+
}
15+
left++;
16+
right--;
17+
}
18+
}
19+
return true;
20+
}
21+
}

csharp/155-Min-Stack.cs

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
public class MinStack {
2+
private Stack<int> stack;
3+
private Stack<int> minStack;
4+
5+
public MinStack() {
6+
stack = new Stack<int>();
7+
minStack = new Stack<int>();
8+
}
9+
10+
public void Push(int val) {
11+
stack.Push(val);
12+
int min = Math.Min(val, minStack.Count != 0 ? minStack.Peek() : val);
13+
minStack.Push(min);
14+
}
15+
16+
public void Pop() {
17+
stack.Pop();
18+
minStack.Pop();
19+
}
20+
21+
public int Top() {
22+
return stack.Peek();
23+
}
24+
25+
public int GetMin() {
26+
return minStack.Peek();
27+
}
28+
}

csharp/167-Two-Sum-II.cs

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
public class Solution {
2+
public int[] TwoSum(int[] numbers, int target) {
3+
// Using 2 pointers. Since sorted, if l+r > target, decrease r.
4+
// Else if l+r < target, increase l. Else, result is found.
5+
int left = 0, right = numbers.Length - 1;
6+
7+
while (left < right) {
8+
int sum = numbers[left] + numbers[right];
9+
if (sum > target) {
10+
right--;
11+
} else if (sum < target) {
12+
left++;
13+
} else {
14+
return new int[] {left + 1, right + 1};
15+
}
16+
}
17+
18+
return new int[0];
19+
}
20+
}

csharp/20-Valid-Parentheses.cs

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
public class Solution {
2+
public bool IsValid(string s) {
3+
var stack = new Stack<char>();
4+
var pairs = new Dictionary<char, char>() {
5+
[')'] = '(',
6+
[']'] = '[',
7+
['}'] = '{'
8+
};
9+
10+
foreach (char c in s) {
11+
if (!pairs.ContainsKey(c)) {
12+
stack.Push(c);
13+
} else if (stack.Count == 0 || stack.Pop() != pairs[c]) {
14+
return false;
15+
}
16+
}
17+
18+
return stack.Count == 0;
19+
}
20+
}

csharp/217-Contains-Duplicate.cs

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
public class Solution {
2+
public bool ContainsDuplicate(int[] nums) {
3+
HashSet<int> set = new HashSet<int>();
4+
5+
foreach (int x in nums){
6+
if (set.Contains(x)) return true;
7+
set.Add(x);
8+
}
9+
return false;
10+
}
11+
}

csharp/242-Valid-Anagram.cs

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
public class Solution {
2+
public bool IsAnagram(string s, string t) {
3+
if (s.Length != t.Length) return false;
4+
if (s == t) return true;
5+
6+
Dictionary<char, int> sCounts = new Dictionary<char, int>();
7+
Dictionary<char, int> tCounts = new Dictionary<char, int>();
8+
9+
for (int i = 0; i < s.Length; i++) {
10+
sCounts[s[i]] = 1 + (sCounts.ContainsKey(s[i]) ? sCounts[s[i]] : 0);
11+
tCounts[t[i]] = 1 + (tCounts.ContainsKey(t[i]) ? tCounts[t[i]] : 0);
12+
}
13+
14+
foreach (char c in sCounts.Keys) {
15+
int tCount = tCounts.ContainsKey(c) ? tCounts[c] : 0;
16+
if (sCounts[c] != tCount) return false;
17+
}
18+
return true;
19+
}
20+
}
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
public class Solution {
2+
public int LengthOfLongestSubstring(string s) {
3+
int leftPointer = 0, rightPointer = 0, maxLength = 0;
4+
HashSet<int> chars = new HashSet<int>();
5+
6+
while (rightPointer < s.Length) {
7+
char currChar = s[rightPointer];
8+
if (chars.Contains(currChar)) { // Move left pointer until all duplicate chars removed
9+
chars.Remove(s[leftPointer]);
10+
leftPointer++;
11+
} else {
12+
chars.Add(currChar);
13+
maxLength = Math.Max(maxLength, rightPointer - leftPointer + 1);
14+
rightPointer++;
15+
}
16+
}
17+
return maxLength;
18+
}
19+
}
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
public class Solution {
2+
public int CharacterReplacement(string s, int k) {
3+
int left = 0, maxLength = 0;
4+
int mostFrequentLetterCount = 0; // Count of most frequent letter in the window
5+
int[] charCounts = new int[26]; // Counts per letter
6+
7+
for (int right = 0; right < s.Length; right++) {
8+
charCounts[s[right] - 'A']++;
9+
mostFrequentLetterCount = Math.Max(mostFrequentLetterCount, charCounts[s[right] - 'A']);
10+
11+
int lettersToChange = (right - left + 1) - mostFrequentLetterCount;
12+
if (lettersToChange > k) { // Window is invalid, decrease char count and move left pointer
13+
charCounts[s[left] - 'A']--;
14+
left++;
15+
}
16+
17+
maxLength = Math.Max(maxLength, (right - left + 1));
18+
}
19+
return maxLength;
20+
}
21+
}

csharp/49-Group-Anagrams.cs

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
public class Solution {
2+
public IList<IList<string>> GroupAnagrams(string[] strs) {
3+
var groups = new Dictionary<string, IList<string>>();
4+
5+
foreach (string s in strs) {
6+
char[] hash = new char[26];
7+
foreach (char c in s) {
8+
hash[c - 'a']++;
9+
}
10+
11+
string key = new string(hash);
12+
if (!groups.ContainsKey(key)) {
13+
groups[key] = new List<string>();
14+
}
15+
groups[key].Add(s);
16+
}
17+
return groups.Values.ToList();
18+
}
19+
}

csharp/704-Binary-Search.cs

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
public class Solution {
2+
public int Search(int[] nums, int target) {
3+
int left = 0, right = nums.Length - 1;
4+
5+
while (left <= right) {
6+
int mid = left + ((right - left) / 2); // (left + right) / 2 can lead to overflow
7+
if (nums[mid] > target) {
8+
right = mid - 1;
9+
} else if (nums[mid] < target) {
10+
left = mid + 1;
11+
} else { // Found the value
12+
return mid;
13+
}
14+
}
15+
return -1;
16+
}
17+
}
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
class Solution {
2+
public int longestConsecutive(int[] nums) {
3+
Set<Integer> set = new HashSet<>();
4+
int max = -1;
5+
int min = 1000000000;
6+
7+
// Find min and max from array & add each to set
8+
for (int i : nums) {
9+
set.add(i);
10+
max = Math.max(max, i);
11+
min = Math.min(min, i);
12+
}
13+
14+
int c = 0; // count streak
15+
int res = 0; // longest streak
16+
for (int i = min; i <= max; ++i) {
17+
// Check if set contains ith value; increment count & remove from set
18+
if (set.contains(i)) {
19+
c++;
20+
set.remove(i);
21+
}
22+
else {
23+
// If not found set count to 0
24+
c = 0;
25+
}
26+
// Find longest streak at every step in case we break out from loop
27+
res = Math.max(res, c);
28+
29+
// If set size is less than current longest streak break as we wont get any longer streak
30+
if (set.size() <= res && c == 0) break;
31+
}
32+
return res;
33+
}
34+
}
File renamed without changes.

0 commit comments

Comments
 (0)