π Approach 1: Sorting (Most Intuitive)
https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/
Space - O(1)
If Array - Sorted
TC - n
else
TC - nlog(n)class Solution {
public:
vector<int> twoSum(vector<int>& arr, int target) {
int s = 0, e = arr.size() - 1;
while (s < e)
{
int sum = arr[s] + arr[e];
if (sum > target) e--;
else if (sum < target) s++;
else return {s + 1, e + 1};
}
return { -1, -1};
}
};π Approach 2: # Β Frequency Count (Optimal)
https://leetcode.com/problems/two-sum/description/
Space - O(n)
If Array - Sorted
TC - n
else
TC - nlog(n)class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
map<vector<int> ,vector<string>> um;
vector<vector<string>> ans;
for(auto &&i: strs)
{
vector<int> freq(26);
for(auto &&j: i)
freq[j-'a']++;
um[freq].push_back(i);
}
for(auto i: um) ans.push_back(i.second);
return ans;
}
};