Skip to content
Merged
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
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
.DS_Store
25 changes: 25 additions & 0 deletions cpp/neetcode_150/01_arrays_&_hashing/contains_duplicate.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
/*
Given int array, return true if any value appears at least twice
Ex. nums = [1,2,3,1] -> true, nums = [1,2,3,4] -> false
If seen num previously then has dupe, else insert into hash set
Time: O(n)
Space: O(n)
*/

class Solution {
public:
bool containsDuplicate(vector<int>& nums) {
unordered_set<int> s;

for (int i = 0; i < nums.size(); i++) {
if (s.find(nums[i]) != s.end()) {
return true;
}
s.insert(nums[i]);
}

return false;
}
};
48 changes: 48 additions & 0 deletions cpp/neetcode_150/01_arrays_&_hashing/encode_and_decode_strings.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
/*
Design algorithm to encode/decode: list of strings <-> string
Encode/decode w/ non-ASCII delimiter: {len of str, "#", str}
Time: O(n)
Space: O(1)
*/

class Codec {
public:

// Encodes a list of strings to a single string.
string encode(vector<string>& strs) {
string result = "";

for (int i = 0; i < strs.size(); i++) {
string str = strs[i];
result += to_string(str.size()) + "#" + str;
}

return result;
}

// Decodes a single string to a list of strings.
vector<string> decode(string s) {
vector<string> result;

int i = 0;
while (i < s.size()) {
int j = i;
while (s[j] != '#') {
j++;
}
int length = stoi(s.substr(i, j - i));
string str = s.substr(j + 1, length);
result.push_back(str);
i = j + 1 + length;
}

return result;
}
private:
};

// Your Codec object will be instantiated and called as such:
// Codec codec;
// codec.decode(codec.encode(strs));
39 changes: 39 additions & 0 deletions cpp/neetcode_150/01_arrays_&_hashing/group_anagrams.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
/*
Given array of strings, group anagrams together (same letters diff order)
Ex. strs = ["eat","tea","tan","ate","nat","bat"] -> [["bat"],["nat","tan"],["ate","eat","tea"]]
Count chars, for each string use total char counts (naturally sorted) as key
Time: O(n x l) -> n = length of strs, l = max length of a string in strs
Space: O(n x l)
*/

class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
unordered_map<string, vector<string>> m;
for (int i = 0; i < strs.size(); i++) {
string key = getKey(strs[i]);
m[key].push_back(strs[i]);
}

vector<vector<string>> result;
for (auto it = m.begin(); it != m.end(); it++) {
result.push_back(it->second);
}
return result;
}
private:
string getKey(string str) {
vector<int> count(26);
for (int j = 0; j < str.size(); j++) {
count[str[j] - 'a']++;
}

string key = "";
for (int i = 0; i < 26; i++) {
key.append(to_string(count[i] + 'a'));
}
return key;
}
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
/*
Given unsorted array, return length of longest consecutive sequence
Ex. nums = [100,4,200,1,3,2] -> 4, longest is [1,2,3,4]
Store in hash set, only check for longer seq if it's the beginning
Time: O(n)
Space: O(n)
*/

class Solution {
public:
int longestConsecutive(vector<int>& nums) {
unordered_set<int> s;
for (int i = 0; i < nums.size(); i++) {
s.insert(nums[i]);
}

int result = 0;

for (auto it = s.begin(); it != s.end(); it++) {
int currNum = *it;
if (s.find(currNum - 1) != s.end()) {
continue;
}
int currLength = 1;
while (s.find(currNum + 1) != s.end()) {
currLength++;
currNum++;
}
result = max(result, currLength);
}

return result;
}
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
/*
Given an integer array nums, return an array such that:
answer[i] is equal to the product of all elements of nums except nums[i]
Ex. nums = [1,2,3,4] -> [24,12,8,6], nums = [-1,1,0,-3,3] -> [0,0,9,0,0]
Calculate prefix products forward, then postfix backwards in a 2nd pass
Time: O(n)
Space: O(1)
*/

class Solution {
public:
vector<int> productExceptSelf(vector<int>& nums) {
int n = nums.size();
vector<int> result(n, 1);

int prefix = 1;
for (int i = 0; i < n; i++) {
result[i] = prefix;
prefix = prefix * nums[i];
}

int postfix = 1;
for (int i = n - 1; i >= 0; i--) {
result[i] = result[i] * postfix;
postfix = postfix * nums[i];
}

return result;
}
};
65 changes: 65 additions & 0 deletions cpp/neetcode_150/01_arrays_&_hashing/top_k_frequent_elements.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
/*
Given an integer array nums & an integer k, return the k most frequent elements
Ex. nums = [1,1,1,2,2,3] k = 2 -> [1,2], nums = [1] k = 1 -> [1]
Heap -> optimize w/ freq map & bucket sort (no freq can be > n), get results from end
*/

// Time: O(n log k)
// Space: O(n + k)

// class Solution {
// public:
// vector<int> topKFrequent(vector<int>& nums, int k) {
// unordered_map<int, int> m;
// for (int i = 0; i < nums.size(); i++) {
// m[nums[i]]++;
// }
// priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;
// for (auto it = m.begin(); it != m.end(); it++) {
// pq.push({it->second, it->first});
// if (pq.size() > k) {
// pq.pop();
// }
// }
// vector<int> result;
// while (!pq.empty()) {
// result.push_back(pq.top().second);
// pq.pop();
// }
// return result;
// }
// };

// Time: O(n)
// Space: O(n)

class Solution {
public:
vector<int> topKFrequent(vector<int>& nums, int k) {
int n = nums.size();

unordered_map<int, int> m;
for (int i = 0; i < n; i++) {
m[nums[i]]++;
}

vector<vector<int>> buckets(n + 1);
for (auto it = m.begin(); it != m.end(); it++) {
buckets[it->second].push_back(it->first);
}

vector<int> result;

for (int i = n; i >= 0; i--) {
if (result.size() >= k) {
break;
}
if (!buckets[i].empty()) {
result.insert(result.end(), buckets[i].begin(), buckets[i].end());
}
}

return result;
}
};
30 changes: 30 additions & 0 deletions cpp/neetcode_150/01_arrays_&_hashing/two_sum.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
/*
Given int array & target, return indices of 2 nums that add to target
Ex. nums = [2,7,11,15] & target = 9 -> [0,1], 2 + 7 = 9
At each num, calculate complement, if exists in hash map then return
Time: O(n)
Space: O(n)
*/

class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int, int> m;
vector<int> result;

for (int i = 0; i < nums.size(); i++) {
int complement = target - nums[i];
if (m.find(complement) != m.end()) {
result.push_back(m[complement]);
result.push_back(i);
break;
} else {
m.insert({nums[i], i});
}
}

return result;
}
};
32 changes: 32 additions & 0 deletions cpp/neetcode_150/01_arrays_&_hashing/valid_anagram.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
/*
Given 2 strings, return true if anagrams (same letters diff order)
Ex. s = "anagram" & t = "nagaram" -> true, s = "rat" & t = "car" -> false
Count chars, strings should have same # of chars if anagram
Time: O(n)
Space: O(26)
*/

class Solution {
public:
bool isAnagram(string s, string t) {
if (s.size() != t.size()) {
return false;
}

vector<int> count(26);

for (int i = 0; i < s.size(); i++) {
count[s[i] - 'a']++;
}

for (int j = 0; j < t.size(); j++) {
count[t[j] - 'a']--;
if (count[t[j] - 'a'] < 0) {
return false;
}
}
return true;
}
};
66 changes: 66 additions & 0 deletions cpp/neetcode_150/01_arrays_&_hashing/valid_sudoku.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
/*
Determine if a 9x9 Sudoku board is valid (no repeats)
Hash set to store seen values, check rows, cols, blocks
Time: O(n^2)
Space: O(n^2)
*/

class Solution {
public:
bool isValidSudoku(vector<vector<char>>& board) {
unordered_set<char> s;

for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
if (board[i][j] == '.') {
continue;
}
auto it = s.find(board[i][j]);
if (it != s.end()) {
return false;
} else {
s.insert(board[i][j]);
}
}
s.clear();
}

for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
if (board[j][i] == '.') {
continue;
}
auto it = s.find(board[j][i]);
if (it != s.end()) {
return false;
} else {
s.insert(board[j][i]);
}
}
s.clear();
}

for (int iCount = 0; iCount < 9; iCount += 3) {
for (int jCount = 0; jCount < 9; jCount += 3) {
for (int i = iCount; i < iCount + 3; i++) {
for (int j = jCount; j < jCount + 3; j++) {
if (board[i][j] == '.') {
continue;
}
auto it = s.find(board[i][j]);
if (it != s.end()) {
return false;
} else {
s.insert(board[i][j]);
}
}
}
s.clear();
}
}

return true;
}
};
Loading