Saturday, September 19, 2020

3. Longest Substring Without Repeating Characters LeetCode

 Time Complexity: O(N) 

class Solution {
public:
int lengthOfLongestSubstring(string s) {
vector< int >cnt(256,0);
int mx = 0;
int st = 0;
for(int i=0; i<(int)s.size(); i++){
cnt[s[i]]++;
if(cnt[ s[i] ] > 1){
for(int j=st; j<i; j++){
cnt[ s[j] ]--;
if( s[i] == s[j] ){
st = j+1;
break;
}
}
}
mx = max(mx, i - st + 1);
}
return mx;
}
};

2. Add Two Numbers LeetCode

Time complexity: O(N)


/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode* root = new ListNode(0);
ListNode* ret = root;
int carry = 0;
while(l1 or l2){
int sum = carry;
if(l1){
sum+= l1->val;
l1=l1->next;
}
if(l2){
sum+= l2->val;
l2=l2->next;
}
carry = sum / 10;
sum = sum % 10;
ret->next = new ListNode(sum);
ret = ret->next;
}
while(l1){
int sum = carry + l1->val;
l1=l1->next;
carry = sum / 10;
sum = sum % 10;
ret->next = new ListNode(sum);
ret = ret->next;
}
while(l2){
int sum = carry + l2->val;
l2=l2->next;
carry = sum / 10;
sum = sum % 10;
ret->next = new ListNode(sum);
ret = ret->next;
}
if(carry){
ret->next = new ListNode(carry);
ret = ret->next;
}
return root->next;
}
};


1. Two Sum LeetCode

C++ STL map solution O(nlogn)


class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
map< int ,int > mp;
vector< int > ans(2, -1);
for(int i=0; i< (int)nums.size(); i++ ){
if( mp.find( target - nums[i] ) != mp.end() ){
return { i, mp[ target - nums[i] ] };
}
mp[ nums[i] ] = i;
}
return ans;
}
};


3. Longest Substring Without Repeating Characters LeetCode

 Time Complexity: O(N)  class Solution { public: int lengthOfLongestSubstring (string s) { vector< int > c...