Skip to content

Commit 7d1802d

Browse files
authored
Merge branch 'neetcode-gh:main' into main
2 parents 76ebfba + 8402bea commit 7d1802d

File tree

117 files changed

+3055
-115
lines changed

Some content is hidden

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

117 files changed

+3055
-115
lines changed

169-Majority Element.cpp

-17
This file was deleted.

554-Brick-Wall.py

-3
This file was deleted.

README.md

+71-71
Large diffs are not rendered by default.

c/0014-Longest-Common-Prefix.c

+21
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
char * longestCommonPrefix(char ** strs, int strsSize){
2+
int commonPrefixCount = 0;
3+
int firstStrSize = strlen(strs[0]);
4+
5+
for(int i = 0; i < firstStrSize; i++)
6+
{
7+
for(int s = 1; s < strsSize; s++)
8+
{
9+
if(i == strlen(strs[s]) || strs[0][i] != strs[s][i])
10+
{
11+
// Add null terminator after the last common prefix char
12+
strs[0][commonPrefixCount] = '\0';
13+
return strs[0];
14+
}
15+
}
16+
17+
commonPrefixCount++;
18+
}
19+
20+
return strs[0];
21+
}

c/0022-generate-parentheses.c

+141
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,141 @@
1+
/*
2+
* Problem: Generate Parentheses (Medium)
3+
* Link: https://leetcode.com/problems/generate-parentheses/
4+
*
5+
* The solution uses a backtracking approach to find all well-formed parantheses
6+
* pairs.
7+
*/
8+
9+
#include <math.h>
10+
#include <stddef.h>
11+
#include <stdio.h>
12+
#include <stdlib.h>
13+
#include <string.h>
14+
15+
/*---------------------------------------------------*/
16+
// Things get easier to manage with this structure
17+
// It will essentially act a minimal version of `std::string`.
18+
// The length of the string is always fixed as we know what the length is going
19+
// to be.
20+
struct _Str
21+
{
22+
char* buf;
23+
int len;
24+
int idx;
25+
} DefStr = { .idx = 0 };
26+
27+
// Doesn't add anything to the code other than convenience of writing `Str ...`
28+
// over `struct _Str ...`
29+
typedef struct _Str Str;
30+
31+
// Pushes a character to the back of the Str
32+
void
33+
push_back(Str* self, char chr)
34+
{
35+
if (self->idx > self->len) {
36+
// Length check
37+
return;
38+
}
39+
self->buf[self->idx++] = chr;
40+
}
41+
42+
// Pops last character from the Str. Add Nullchar at the end just to signify the
43+
// end of string.
44+
void
45+
pop_back(Str* self)
46+
{
47+
if (self->idx == 0) {
48+
return;
49+
}
50+
self->buf[self->idx--] = '\0';
51+
}
52+
53+
/*---------------------------------------------------*/
54+
55+
/*
56+
* This problem can be reduced to a subsets problem, where we explore every
57+
* possible parantheses combination and keep the valid ones.
58+
*
59+
* To do so, we will --
60+
* 1. Generate a combination
61+
* 2. Check if it is balanced
62+
* 3. Backtrack
63+
* 4. Repeat
64+
*/
65+
void
66+
backtrack(char** results,
67+
int n,
68+
int open,
69+
int closed,
70+
Str* curr,
71+
int* returnSize)
72+
{
73+
if (closed > open) {
74+
// This is the case when we prune the exploration of not well-formed
75+
// parentheses
76+
return;
77+
}
78+
if (open + closed == 2 * n) {
79+
// ^ checking lengths
80+
// Create a copy of the qualifying buffer and save it in Results
81+
// wf = well-formed
82+
results[*returnSize] = (char*)calloc(2 * n + 1, sizeof(char));
83+
memcpy(results[*returnSize], curr->buf, 2 * n);
84+
*returnSize = *returnSize + 1;
85+
return;
86+
}
87+
88+
if (open < n) {
89+
// If we do not have enough opening brackets, add one till we have `n`
90+
push_back(curr, '(');
91+
backtrack(results, n, open + 1, closed, curr, returnSize);
92+
93+
// Pop this so that we can explore the other combinations
94+
pop_back(curr);
95+
}
96+
97+
if (closed < n) {
98+
// If we do not have enough closing brackets, add one till we have `n`
99+
push_back(curr, ')');
100+
backtrack(results, n, open, closed + 1, curr, returnSize);
101+
102+
// Pop this so that we can explore the other combinations
103+
pop_back(curr);
104+
}
105+
}
106+
107+
/**
108+
* Note: The returned array must be malloced, assume caller calls free().
109+
*/
110+
char**
111+
generateParenthesis(int n, int* returnSize)
112+
{
113+
/*
114+
* Allocate enough memory for maximum possible combinations
115+
* The maximum would ideally be every possible combination (included invalid
116+
* ones). This is 2^(len of combination) == 2^(2 * n)
117+
*
118+
* Ofc, we will need less memory than this, but its fine.
119+
*
120+
* In the worst case according to our constraints, n = 9.
121+
* In this case, we will allocate 2^9 * 8 = 4096 bytes, which is 4KB. So we
122+
* can be sure that this program won't hog **too** much memory.
123+
*/
124+
125+
char** results = (char**)malloc(pow(2, 2 * n) * sizeof(char*));
126+
127+
// Length is excluding null character, calloc includes null character
128+
// Calloc because it zeroes out our memory, so we automatically get a null
129+
// character.
130+
Str current = { .len = 2 * n, .buf = (char*)calloc(2 * n + 1, sizeof(char)) };
131+
132+
// We backtrack.
133+
*returnSize = 0;
134+
backtrack(results, n, 0, 0, &current, returnSize);
135+
136+
// Free the Str buffer as we won't need it now.
137+
free(current.buf);
138+
139+
// Return results
140+
return results;
141+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
/**
2+
* Note: The returned array must be malloced, assume caller calls free().
3+
*/
4+
int* findDisappearedNumbers(int* nums, int numsSize, int* returnSize){
5+
int* disappearedNumbers = (int*)malloc(numsSize * sizeof(int)); // Allocate space for the worst case
6+
*returnSize = 0; // Points to the first empty index in the array
7+
8+
// Mark available numbers as negative
9+
for(int i = 0; i < numsSize; i++)
10+
{
11+
int index = abs(nums[i]);
12+
nums[index - 1] = -1 * abs(nums[index - 1]);
13+
}
14+
15+
// Find unmarked numbers (disappeared numbers)
16+
for(int i = 0; i < numsSize; i++)
17+
{
18+
if(nums[i] > 0)
19+
{
20+
disappearedNumbers[(*returnSize)++] = i + 1;
21+
}
22+
}
23+
24+
return disappearedNumbers;
25+
}

c/0980-unique-paths-iii.c

+49
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
const int OBSTACLE = -1, EMPTY = 0, START = 1, END = 2;
2+
int uniquePathsIII(int** grid, int gridSize, int* gridColSize){
3+
int startRow, startCol, endRow, endCol,
4+
toVisit = 0, visited = 0, R = gridSize, C = gridColSize[0];
5+
for(int row = 0; row < R; row++)
6+
for(int col = 0; col < C; col++) {
7+
//dereference the value of the current cell
8+
int cell = grid[row][col];
9+
if(cell != OBSTACLE) {
10+
//all non obstacle cells must be visited
11+
toVisit++;
12+
//remember start and end cells
13+
if(cell == START) {
14+
startRow = row;
15+
startCol = col;
16+
} else if(cell == END) {
17+
endRow = row;
18+
endCol = col;
19+
}
20+
} else
21+
//obstacles can be considered visited cells
22+
visited |= 1 << (row*C + col);
23+
}
24+
25+
//The starting state is an empty path which will visit the start cell next
26+
return solve(R, C, endRow, endCol, visited, toVisit, startRow, startCol);
27+
}
28+
29+
int solve(int R, int C, int endRow, int endCol, int visited, int toVisit, int row, int col){
30+
toVisit--;
31+
//base case, we are at the end cell.
32+
if(row == endRow && col == endCol)
33+
return !toVisit;
34+
35+
//add current cell to visited set
36+
visited |= 1 << (row*C + col);
37+
38+
//count paths which go through all other valid neighbor cells.
39+
int ret = 0;
40+
if(row > 0 && !(visited & (1 << ((row - 1)*C + col))))
41+
ret += solve(R, C, endRow, endCol, visited, toVisit, row - 1, col);
42+
if(row + 1 < R && !(visited & (1 << ((row + 1)*C + col))))
43+
ret += solve(R, C, endRow, endCol, visited, toVisit, row + 1, col);
44+
if(col > 0 && !(visited & (1 << (row*C + col - 1))))
45+
ret += solve(R, C, endRow, endCol, visited, toVisit, row, col - 1);
46+
if(col + 1 < C && !(visited & (1 << (row*C + col + 1))))
47+
ret += solve(R, C, endRow, endCol, visited, toVisit, row, col + 1);
48+
return ret;
49+
}
+18
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
class Solution {
2+
public:
3+
int guessNumber(int n) {
4+
int low = 1;
5+
int high = n;
6+
7+
while(true) {
8+
int mid = low + (high - low)/2;
9+
int myGuess = guess(mid);
10+
if(myGuess == 1)
11+
low = mid + 1;
12+
else if(myGuess == -1)
13+
high = mid - 1;
14+
else
15+
return mid;
16+
}
17+
}
18+
};

cpp/0496-next-greater-element.cpp

+32
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
class Solution {
2+
public:
3+
vector<int> nextGreaterElement(vector<int>& nums1, vector<int>& nums2) {
4+
// O (n + m)
5+
map<int, int> nums1Idx; {
6+
int idx = 0;
7+
for(int n: nums1)
8+
nums1Idx[n] = idx++;
9+
}
10+
vector<int> res;
11+
for(int i = 0; i < nums1.size(); i++)
12+
res.push_back(-1);
13+
14+
stack<int> stack;
15+
for(int i = 0; i < nums2.size(); i++) {
16+
int cur = nums2[i];
17+
18+
// while stack has elements and current is greater than the top of the stack
19+
while(stack.size() && cur > stack.top()) {
20+
int val = stack.top(); // take top val
21+
stack.pop();
22+
int idx = nums1Idx[val];
23+
res[idx] = cur;
24+
}
25+
26+
if(nums1Idx.count(cur))
27+
stack.push(cur);
28+
}
29+
30+
return res;
31+
}
32+
};
+21
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
class Solution {
2+
private:
3+
map<string, string> encodeMap;
4+
map<string, string> decodeMap;
5+
string base = "http://tinyurl.com/";
6+
public:
7+
// Encodes a URL to a shortened URL.
8+
string encode(string longUrl) {
9+
if(!encodeMap.count(longUrl)) {
10+
string shortUrl = base + to_string(encodeMap.size() + 1);
11+
encodeMap[longUrl] = shortUrl;
12+
decodeMap[shortUrl] = longUrl;
13+
}
14+
return encodeMap[longUrl];
15+
}
16+
17+
// Decodes a shortened URL to its original URL.
18+
string decode(string shortUrl) {
19+
return decodeMap[shortUrl];
20+
}
21+
};

cpp/0680-valid-palindrome-ii.cpp

+24
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
class Solution {
2+
private:
3+
bool validPalindromeUtil(string s, int i, int j) {
4+
while(i < j)
5+
if(s[i] == s[j]) {
6+
i += 1;
7+
j -= 1;
8+
} else
9+
return false;
10+
return true;
11+
}
12+
public:
13+
bool validPalindrome(string s) {
14+
int i = 0, j = s.length() - 1;
15+
16+
while(i < j)
17+
if(s[i] == s[j]) {
18+
i += 1;
19+
j -= 1;
20+
} else
21+
return validPalindromeUtil(s, i + 1, j) || validPalindromeUtil(s, i, j - 1);
22+
return true;
23+
}
24+
};

cpp/0929-unique-email-addresses.cpp

+15
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
class Solution {
2+
public:
3+
int numUniqueEmails(vector<string>& emails) {
4+
set<string> unique_emails;
5+
for(string email: emails) {
6+
string local_name = email.substr(0, email.find('@'));
7+
local_name = local_name.substr(0, email.find('+'));
8+
local_name = regex_replace(local_name, regex("\\."), "");
9+
string domain_name = email.substr(email.find('@') + 1, email.length());
10+
email = local_name + '@' + domain_name;
11+
unique_emails.insert(email);
12+
}
13+
return unique_emails.size();
14+
}
15+
};
+16
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
class Solution {
2+
public:
3+
int maxNumberOfBalloons(string text) {
4+
map<char, int> countText;
5+
map<char, int> balloon;
6+
for(char c: text)
7+
countText[c]++;
8+
for(char c: std::string("balloon"))
9+
balloon[c]++;
10+
11+
int res = text.length();
12+
for(const auto &[key, value]: balloon)
13+
res = min(res, countText[key] / value);
14+
return res;
15+
}
16+
};

0 commit comments

Comments
 (0)