├── .gitignore ├── C++ ├── #deleteDuplicatesii.cpp# ├── 3sum.cpp ├── addTwoNumber.cpp ├── arrange.cpp ├── atoi.cpp ├── binarySearch.cpp ├── braces.cpp ├── compareNum.cpp ├── convert.cpp ├── convertToTitle.cpp ├── coverPoints.cpp ├── deleteDuplicatesi.cpp ├── deleteDuplicatesii.cpp ├── detectCycle.cpp ├── diagonal.cpp ├── duplicate.cpp ├── evalRPN.cpp ├── findCount.cpp ├── findMin.cpp ├── gcd.cpp ├── generateMatrix.cpp ├── generatePascal.cpp ├── getIntersectionNode.cpp ├── intersect.cpp ├── isPalindrome.cpp ├── isPower.cpp ├── largestNum.cpp ├── lengthofLastWord.cpp ├── listPalindrome.cpp ├── longestCommonPrefix.cpp ├── longestPalindrome.cpp ├── maxArea.cpp ├── maxSet.cpp ├── maxSubArray.cpp ├── mergeIntervals.cpp ├── mergeTwoLists.cpp ├── minStack.cpp ├── numSetBits.cpp ├── partition.cpp ├── pow.cpp ├── prevSmaller.cpp ├── primeSum.cpp ├── removeNthFromEnd.cpp ├── reorderList.cpp ├── repeatedNum.cpp ├── reverse.cpp ├── reverseBetween.cpp ├── roman2int.cpp ├── rotate.cpp ├── rotateRight.cpp ├── rotatedsearch.cpp ├── searchInsert.cpp ├── searchMatrix.cpp ├── setMatrixZeros.cpp ├── singleNumberi.cpp ├── singleNumberii.cpp ├── sqrt.cpp ├── substr.cpp ├── swapColor.cpp ├── titleToNumber.cpp ├── trailingZeros.cpp ├── uniquePaths.cpp └── wave.cpp ├── LICENSE ├── Python ├── __init__.py ├── addTwoNumbers.py ├── addone.py ├── arrange.py ├── convertToTitle.py ├── detectCycle.py ├── flip.py ├── gcd.py ├── generateMatrix.py ├── generatePascal.py ├── getRow.py ├── isPalindrome.py ├── isPower.py ├── maxSet.py ├── nextPermutation.py ├── partition.py ├── primeSum.py ├── reorderList.py ├── reverse.py ├── titleToNumber.py ├── trailingZeros.py └── uniquePaths.py ├── README.md ├── README.org ├── img └── ib-logo-square.png ├── repeatedNumber.py └── timeComplexity.md /.gitignore: -------------------------------------------------------------------------------- 1 | .idea 2 | /Python/__init__.py -------------------------------------------------------------------------------- /C++/#deleteDuplicatesii.cpp#: -------------------------------------------------------------------------------- 1 | ListNode* Solution::deleteDuplicates(ListNode *head) { 2 | if (head == NULL) return NULL; 3 | ListNode* fakeHead = new ListNode(0); 4 | fakeHead->next = head; 5 | ListNode* pre = fakeHead; 6 | ListNode* cur = head; 7 | while (cur != NULL) { 8 | while (cur->next != NULL && cur->val == cur->next->val) { 9 | cur = cur->next; 10 | } 11 | if (pre->next == cur) { 12 | pre = pre->next; 13 | } else { 14 | pre->next = cur->next; 15 | } 16 | cur = cur->next; 17 | } 18 | return fakeHead->next; 19 | } 20 | -------------------------------------------------------------------------------- /C++/3sum.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int threeSumClosest(vector &num, int target) { 4 | sort(num.begin(), num.end()); 5 | int bestSum = 1000000000, sum = 0; 6 | // Fix the smallest number in the three integers 7 | for (int i = 0; i < num.size() - 2; i++) { 8 | // Now num[i] is the smallest number in the three integers in the solution 9 | int ptr1 = i + 1, ptr2 = num.size() - 1; 10 | while (ptr1 < ptr2) { 11 | sum = num[i] + num[ptr1] + num[ptr2]; 12 | if (abs(target - sum) < abs(target - bestSum)) { 13 | bestSum = sum; 14 | } 15 | if (sum > target) { 16 | ptr2--; 17 | } else { 18 | ptr1++; 19 | } 20 | } 21 | } 22 | return bestSum; 23 | } 24 | }; 25 | -------------------------------------------------------------------------------- /C++/addTwoNumber.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) { 4 | if(!l1) 5 | return l2; 6 | if(!l2) 7 | return l1; 8 | 9 | int carry = (l1->val + l2->val) / 10; 10 | ListNode *l3 = new ListNode((l1->val + l2->val) % 10); 11 | ListNode *tail = l3; 12 | l1 = l1->next; 13 | l2 = l2->next; 14 | 15 | while(l1 || l2 || carry) 16 | { 17 | int sum = ((l1 ? l1->val : 0) + (l2 ? l2->val : 0) + carry); 18 | ListNode *t = new ListNode(sum % 10); 19 | carry = sum / 10; 20 | 21 | if(l1) 22 | l1 = l1->next; 23 | if(l2) 24 | l2 = l2->next; 25 | tail->next = t; 26 | tail = t; 27 | } 28 | 29 | return l3; 30 | } 31 | }; 32 | -------------------------------------------------------------------------------- /C++/arrange.cpp: -------------------------------------------------------------------------------- 1 | void Solution::arrange(vector &Vec) { 2 | // Do not write main() function. 3 | // Do not read input, instead use the arguments to the function. 4 | // Do not print the output, instead return values as specified 5 | // Still have a doubt. Checkout www.interviewbit.com/pages/sample_codes/ for more details 6 | int N = Vec.size(); 7 | for(int i = 0; i < N; ++i) { 8 | Vec[i] = Vec[i] + (Vec[Vec[i]]%N) * N; 9 | } 10 | 11 | for(int i = 0; i < N; ++i) { 12 | Vec[i] = Vec[i] / N; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /C++/atoi.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int atoi(const string &str) { 4 | int sign = 1, base = 0, i = 0; 5 | while (str[i] == ' ') { i++; } 6 | if (str[i] == '-' || str[i] == '+') { 7 | sign = (str[i++] == '-') ? -1 : 1; 8 | } 9 | while (str[i] >= '0' && str[i] <= '9') { 10 | if (base > INT_MAX / 10 || (base == INT_MAX / 10 && str[i] - '0' > 7)) { 11 | if (sign == 1) return INT_MAX; 12 | else return INT_MIN; 13 | } 14 | base = 10 * base + (str[i++] - '0'); 15 | } 16 | return base * sign; 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /C++/binarySearch.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int binarySearch(int A[], int n, int x) 5 | { 6 | int low = 0, high = n-1; 7 | while(low <= high){ 8 | int mid = (low+high)/2; 9 | if(x == A[mid]) 10 | return mid; 11 | else if(x < A[mid]) 12 | high = mid - 1; 13 | else 14 | low = mid + 1; 15 | } 16 | return -1; 17 | } 18 | 19 | int main() 20 | { 21 | int A[] = {2,4,5,7,13,14,15,23}; 22 | std::cout << "Enter a number: "; 23 | int x; 24 | std::cin >> x; 25 | int index = binarySearch(A,8,x); 26 | if(index != -1) 27 | std::cout << "Number " << x << " is at index " << index << std::endl; 28 | else 29 | std::cout << "Number " << x << " not found" << std::endl; 30 | } 31 | -------------------------------------------------------------------------------- /C++/braces.cpp: -------------------------------------------------------------------------------- 1 | int braces(string str) 2 | { 3 | stack Stack; 4 | 5 | for(int i = 0; i < str.size(); ++i) { 6 | if(str[i] == ')') { 7 | int count = 0; 8 | while(Stack.top() != '(') { 9 | Stack.pop(); 10 | count++; 11 | } 12 | Stack.pop(); 13 | if(count < 2) 14 | return 1; 15 | } else { 16 | Stack.push(str[i]); 17 | } 18 | } 19 | 20 | bool redundant = true; 21 | 22 | while(Stack.size()) { 23 | if(Stack.top() == '(' || Stack.top() == ')') { 24 | redundant = false; 25 | break; 26 | } 27 | Stack.pop(); 28 | } 29 | 30 | if(!redundant) 31 | return 1; 32 | return 0; 33 | } 34 | }; 35 | -------------------------------------------------------------------------------- /C++/compareNum.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | static bool compareNum(string a, string b) { 4 | return a + b > b + a; 5 | } 6 | 7 | string largestNumber(const vector &num) { 8 | string result; 9 | vector str; 10 | for (int i = 0; i < num.size(); i++) { 11 | str.push_back(to_string(num[i])); 12 | } 13 | sort(str.begin(), str.end(), compareNum); 14 | for (int i = 0; i < str.size(); i++) { 15 | result += str[i]; 16 | } 17 | 18 | int pos = 0; 19 | while (result[pos] == '0' && pos + 1 < result.size()) pos++; 20 | return result.substr(pos); 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /C++/convert.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string convert(string s, int nRows) { 4 | 5 | if (nRows <= 1) 6 | return s; 7 | 8 | const int len = (int)s.length(); 9 | string *str = new string[nRows]; 10 | 11 | int row = 0, step = 1; 12 | for (int i = 0; i < len; ++i) 13 | { 14 | str[row].push_back(s[i]); 15 | 16 | if (row == 0) 17 | step = 1; 18 | else if (row == nRows - 1) 19 | step = -1; 20 | 21 | row += step; 22 | } 23 | 24 | s.clear(); 25 | for (int j = 0; j < nRows; ++j) 26 | { 27 | s.append(str[j]); 28 | } 29 | 30 | return s; 31 | } 32 | 33 | }; 34 | -------------------------------------------------------------------------------- /C++/convertToTitle.cpp: -------------------------------------------------------------------------------- 1 | string convertToTitle(int n) { 2 | string ans; 3 | while (n) { 4 | ans = char ((n - 1) % 26 + 'A') + ans; 5 | n = (n - 1) / 26; 6 | } 7 | return ans; 8 | } 9 | -------------------------------------------------------------------------------- /C++/coverPoints.cpp: -------------------------------------------------------------------------------- 1 | // Input : X and Y co-ordinates of the points in order. 2 | // Each point is represented by (X[i], Y[i]) 3 | int Solution::coverPoints(vector &x, vector &y) { 4 | if (x.size() <= 1) return 0; 5 | assert(x.size() == y.size()); 6 | int ans = 0; 7 | for (int i = 1; i < x.size(); i++) { 8 | ans += max(abs(x[i] - x[i-1]), abs(y[i] - y[i-1])); 9 | } 10 | return ans; 11 | } 12 | -------------------------------------------------------------------------------- /C++/deleteDuplicatesi.cpp: -------------------------------------------------------------------------------- 1 | ListNode *deleteDuplicates(ListNode *head) { 2 | ListNode *origin = head; 3 | while (head != NULL) { 4 | while(head->next != NULL && head->val == head->next->val) { 5 | head->next = head->next->next; 6 | } 7 | head = head->next; 8 | } 9 | return origin; 10 | } 11 | -------------------------------------------------------------------------------- /C++/deleteDuplicatesii.cpp: -------------------------------------------------------------------------------- 1 | Solution::deleteDuplicates(ListNode *head) { 2 | if (head == NULL) return NULL; 3 | ListNode* fakeHead = new ListNode(0); 4 | fakeHead->next = head; 5 | ListNode* pre = fakeHead; 6 | ListNode* cur = head; 7 | while (cur != NULL) { 8 | while (cur->next != NULL && cur->val == cur->next->val) { 9 | cur = cur->next; 10 | } 11 | if (pre->next == cur) { 12 | pre = pre->next; 13 | } else { 14 | pre->next = cur->next; 15 | } 16 | cur = cur->next; 17 | } 18 | return fakeHead->next; 19 | } 20 | -------------------------------------------------------------------------------- /C++/detectCycle.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | ListNode *detectCycle(ListNode *head) { 4 | if (head == NULL || head->next == NULL) return NULL; 5 | 6 | ListNode* firstp = head; 7 | ListNode* secondp = head; 8 | bool isCycle = false; 9 | 10 | while(firstp != NULL && secondp != NULL) { 11 | firstp = firstp->next; 12 | if (secondp->next == NULL) return NULL; 13 | secondp = secondp->next->next; 14 | if (firstp == secondp) { isCycle = true; break; } 15 | } 16 | 17 | if(!isCycle) return NULL; 18 | firstp = head; 19 | while( firstp != secondp) { 20 | firstp = firstp->next; 21 | secondp = secondp->next; 22 | } 23 | 24 | return firstp; 25 | 26 | } 27 | }; 28 | -------------------------------------------------------------------------------- /C++/diagonal.cpp: -------------------------------------------------------------------------------- 1 | vector > Solution::diagonal(vector > &A) { 2 | int i=0,j=0,x,y; 3 | int n=A.size(); 4 | vector> v; 5 | vector row; 6 | i=0;j=0; 7 | while(i=0 ){ 10 | row.push_back(A[x][y]); 11 | x++;y--; 12 | } 13 | v.push_back(row); 14 | row.clear(); 15 | if(j &A) { 2 | // Do not write main() function. 3 | // Do not read input, instead use the arguments to the function. 4 | // Do not print the output, instead return values as specified 5 | // Still have a doubt. Checkout www.interviewbit.com/pages/sample_codes/ for more details 6 | int slow = A[0]; 7 | int fast = A[A[0]]; 8 | while (slow != fast) { 9 | slow = A[slow]; 10 | fast = A[A[fast]]; 11 | } 12 | 13 | fast = 0; 14 | while (slow != fast) { 15 | slow = A[slow]; 16 | fast = A[fast]; 17 | } 18 | return slow; 19 | } 20 | -------------------------------------------------------------------------------- /C++/evalRPN.cpp: -------------------------------------------------------------------------------- 1 | int evalRPN(vector &tokens) { 2 | stack st; 3 | for(int i = 0; i < tokens.size(); ++i) { 4 | if(tokens[i] == "+" || tokens[i] == "-" || tokens[i] == "*" || tokens[i] == "/") { 5 | int v1=st.top(); 6 | st.pop(); 7 | int v2=st.top(); 8 | st.pop(); 9 | switch(tokens[i][0]) { 10 | case '+': 11 | st.push(v2 + v1); 12 | break; 13 | case '-': 14 | st.push(v2 - v1); 15 | break; 16 | case '*': 17 | st.push(v2 * v1); 18 | break; 19 | case '/': 20 | st.push(v2 / v1); 21 | break; 22 | } 23 | } else { 24 | st.push(atoi(tokens[i].c_str())); 25 | } 26 | } 27 | return st.top(); 28 | } 29 | -------------------------------------------------------------------------------- /C++/findCount.cpp: -------------------------------------------------------------------------------- 1 | int findCount(const vector &A, int target) { 2 | int n = A.size(); 3 | int i = 0, j = n - 1; 4 | int start = -1, end = -1; 5 | 6 | // FIND FIRST 7 | while (i < j) 8 | { 9 | int mid = (i + j) /2; 10 | if (A[mid] < target) i = mid + 1; 11 | else j = mid; 12 | } 13 | if (A[i] != target) return 0; // the element does not exist in the array. 14 | 15 | start = i; 16 | 17 | // FINDLAST 18 | j = n - 1; // We don't have to set i to 0 the second time. 19 | while (i < j) 20 | { 21 | int mid = (i + j) /2 + 1; // Make mid biased to the right 22 | if (A[mid] > target) j = mid - 1; 23 | else i = mid; // So that this won't make the search range stuck. 24 | } 25 | end = j; 26 | return (end - start + 1); 27 | } 28 | -------------------------------------------------------------------------------- /C++/findMin.cpp: -------------------------------------------------------------------------------- 1 | int Solution::findMin(const vector &A) { 2 | // Do not write main() function. 3 | // Do not read input, instead use the arguments to the function. 4 | // Do not print the output, instead return values as specified 5 | // Still have a doubt. Checkout www.interviewbit.com/pages/sample_codes/ for more details 6 | int len = A.size(),low = 0, high = len-1; 7 | 8 | while(low <= high){ 9 | if(A[low] <= A[high]) return A[low]; //case 1 10 | int mid = (low + high)/2; 11 | int next = (mid+1)%len, prev = (mid+len-1)%len; 12 | if(A[mid] <= A[next] && A[mid] <= A[prev]) //case 2 13 | return A[mid]; 14 | else if (A[mid] <= A[high]) //case 3 15 | high = mid - 1; 16 | else if (A[mid] >= A[low]) //case 4 17 | low = mid + 1; 18 | } 19 | return -1; 20 | } 21 | 22 | 23 | 24 | -------------------------------------------------------------------------------- /C++/gcd.cpp: -------------------------------------------------------------------------------- 1 | int Solution::gcd(int A, int B) { 2 | if(A==0) 3 | return B; 4 | else if(B==0) 5 | return A; 6 | int y=1; 7 | while(y>0){ 8 | y=A%B; 9 | A=B; 10 | B=y; 11 | } 12 | return A; 13 | } 14 | -------------------------------------------------------------------------------- /C++/generateMatrix.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector > generateMatrix(int n) { 4 | int dir = 0; 5 | vector< vector > matrix(n, vector (n, 0)); 6 | int i = 0, j = 0, k = 1; 7 | while (k <= n * n) { 8 | matrix[i][j] = k++; 9 | if (dir == 0){ 10 | j++; 11 | if (j == n || matrix[i][j] != 0) dir = 1, j--, i++; 12 | } else 13 | if (dir == 1) { 14 | i++; 15 | if (i == n || matrix[i][j] != 0) dir = 2, i--, j--; 16 | } else 17 | if (dir == 2) { 18 | j--; 19 | if (j < 0 || matrix[i][j] != 0) dir = 3, j++, i--; 20 | } else 21 | if (dir == 3) { 22 | i--; 23 | if (i < 0 || matrix[i][j] != 0) dir = 0, i++, j++; 24 | } 25 | } 26 | return matrix; 27 | } 28 | }; 29 | -------------------------------------------------------------------------------- /C++/generatePascal.cpp: -------------------------------------------------------------------------------- 1 | vector > Solution::generate(int A) { 2 | vector > ans; 3 | if (A <= 0) { 4 | return ans; 5 | } 6 | vector temp; 7 | temp.push_back(1); 8 | ans.push_back(temp); 9 | 10 | for (int r = 0; r < A - 1; r++) { 11 | 12 | vector newRow; 13 | newRow.push_back(1); 14 | 15 | for (int c = 0; c < ans[r].size() - 1; c++) { 16 | newRow.push_back(ans[r][c] + ans[r][c + 1]); 17 | } 18 | 19 | newRow.push_back(1); 20 | ans.push_back(newRow); 21 | 22 | } 23 | return ans; 24 | } 25 | 26 | -------------------------------------------------------------------------------- /C++/getIntersectionNode.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode(int x) : val(x), next(NULL) {} 7 | * }; 8 | */ 9 | int getLength(ListNode *head) { 10 | int ret = 0; 11 | while (head) { 12 | ret++; 13 | head = head->next; 14 | } 15 | return ret; 16 | } 17 | ListNode* Solution::getIntersectionNode(ListNode* A, ListNode* B) { 18 | if(!A || !B) 19 | return NULL; 20 | int lenA = getLength(A), lenB = getLength(B); 21 | int lenDiff = lenA - lenB; 22 | ListNode *pa = A; 23 | ListNode *pb = B; 24 | if(lenDiff > 0) { 25 | while(lenDiff != 0) { 26 | pa = pa->next; 27 | lenDiff--; 28 | } 29 | } 30 | else if(lenDiff < 0) { 31 | while(lenDiff != 0) { 32 | pb = pb->next; 33 | lenDiff++; 34 | } 35 | } 36 | while(pa && pb) { 37 | if(pa == pb) 38 | return pa; 39 | pa = pa->next; 40 | pb = pb->next; 41 | } 42 | return NULL; 43 | } 44 | -------------------------------------------------------------------------------- /C++/intersect.cpp: -------------------------------------------------------------------------------- 1 | vector Solution::intersect(const vector &A, const vector &B) { 2 | // Do not write main() function. 3 | // Do not read input, instead use the arguments to the function. 4 | // Do not print the output, instead return values as specified 5 | // Still have a doubt. Checkout www.interviewbit.com/pages/sample_codes/ for more details 6 | vector dups; 7 | int i = 0, j = 0; 8 | int n = A.size(), m = B.size(); 9 | while(iB[j]) j++; 16 | else 17 | i++; 18 | } 19 | return dups; 20 | } 21 | -------------------------------------------------------------------------------- /C++/isPalindrome.cpp: -------------------------------------------------------------------------------- 1 | bool Solution::isPalindrome(int A) { 2 | if(A<0) 3 | return false; 4 | int tenPow[10]={1,10,100,1000,10000,100000,1000000,10000000,100000000,1000000000}; 5 | int i=0; 6 | int noOfDigits=0; 7 | while(i<10 && A/tenPow[i]>0) i++; 8 | noOfDigits=i; 9 | if(noOfDigits==1) 10 | return true; 11 | int B=A; 12 | int C=0; 13 | int temp; 14 | for(i=0;i b + a; 5 | } 6 | 7 | string largestNumber(const vector &num) { 8 | string result; 9 | vector str; 10 | for (int i = 0; i < num.size(); i++) { 11 | str.push_back(to_string(num[i])); 12 | } 13 | sort(str.begin(), str.end(), compareNum); 14 | for (int i = 0; i < str.size(); i++) { 15 | result += str[i]; 16 | } 17 | 18 | int pos = 0; 19 | while (result[pos] == '0' && pos + 1 < result.size()) pos++; 20 | return result.substr(pos); 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /C++/lengthofLastWord.cpp: -------------------------------------------------------------------------------- 1 | int lengthOfLastWord(const string &s) { 2 | int len = 0; 3 | while (*s) { 4 | if (*s != ' ') { 5 | len++; 6 | s++; 7 | continue; 8 | } 9 | s++; 10 | if (*s && *s != ' ') len = 0; 11 | } 12 | return len; 13 | 14 | } 15 | -------------------------------------------------------------------------------- /C++/listPalindrome.cpp: -------------------------------------------------------------------------------- 1 | void reverse(struct ListNode** head_ref) 2 | { 3 | struct ListNode* prev = NULL; 4 | struct ListNode* current = *head_ref; 5 | struct ListNode* next; 6 | while (current != NULL) 7 | { 8 | next = current->next; 9 | current->next = prev; 10 | prev = current; 11 | current = next; 12 | } 13 | *head_ref = prev; 14 | } 15 | 16 | /* Function to check if two input lists have same val*/ 17 | bool compareLists(struct ListNode* head1, struct ListNode *head2) 18 | { 19 | struct ListNode* temp1 = head1; 20 | struct ListNode* temp2 = head2; 21 | 22 | while (temp1 && temp2) 23 | { 24 | if (temp1->val == temp2->val) 25 | { 26 | temp1 = temp1->next; 27 | temp2 = temp2->next; 28 | } 29 | else return 0; 30 | } 31 | 32 | /* Both are empty reurn 1*/ 33 | if (temp1 == NULL && temp2 == NULL) 34 | return 1; 35 | 36 | /* Will reach here when one is NULL 37 | and other is not */ 38 | return 0; 39 | } 40 | 41 | int Solution::lPalin(ListNode* A) { 42 | struct ListNode *slow_ptr = A, *fast_ptr = A; 43 | struct ListNode *second_half, *prev_of_slow_ptr = A; 44 | struct ListNode *midnode = NULL; // To handle odd size list 45 | int res = true; // initialize result 46 | 47 | if (A!=NULL && A->next!=NULL) //to handle if A == 0 48 | { 49 | /* Get the middle of the list. Move slow_ptr by 1 50 | and fast_ptrr by 2, slow_ptr will have the middle 51 | ListNode */ 52 | while (fast_ptr != NULL && fast_ptr->next != NULL) 53 | { 54 | fast_ptr = fast_ptr->next->next; 55 | 56 | /*We need previous of the slow_ptr for 57 | linked lists with odd elements */ 58 | prev_of_slow_ptr = slow_ptr; 59 | slow_ptr = slow_ptr->next; 60 | } 61 | 62 | 63 | /* fast_ptr would become NULL when there are even elements in list. 64 | And not NULL for odd elements. We need to skip the middle ListNode 65 | for odd case and store it somewhere so that we can restore the 66 | original list*/ 67 | if (fast_ptr != NULL) 68 | { 69 | midnode = slow_ptr; 70 | slow_ptr = slow_ptr->next; 71 | } 72 | 73 | // Now reverse the second half and compare it with first half 74 | second_half = slow_ptr; 75 | prev_of_slow_ptr->next = NULL; // NULL terminate first half 76 | reverse(&second_half); // Reverse the second half 77 | res = compareLists(A, second_half); // compare 78 | 79 | } 80 | return res; 81 | } 82 | -------------------------------------------------------------------------------- /C++/longestCommonPrefix.cpp: -------------------------------------------------------------------------------- 1 | string Solution::longestCommonPrefix(vector &A) { 2 | // Do not write main() function. 3 | // Do not read input, instead use the arguments to the function. 4 | // Do not print the output, instead return values as specified 5 | // Still have a doubt. Checkout www.interviewbit.com/pages/sample_codes/ for more details 6 | if(A.empty()) 7 | return ""; 8 | 9 | for(int i = 0; i < A[0].length(); i++){ 10 | for(const auto &str : A){ 11 | if(i > str.length() || str[i] != A[0][i]){ 12 | return A[0].substr(0, i); 13 | } 14 | } 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /C++/longestPalindrome.cpp: -------------------------------------------------------------------------------- 1 | string preProcess(const string& s) { 2 | if (s.empty()) { 3 | return "^$"; 4 | } 5 | string ret = "^"; 6 | for (int i = 0; i < s.length(); ++i) { 7 | ret += "#" + s.substr(i, 1); 8 | } 9 | ret += "#$"; 10 | return ret; 11 | } 12 | 13 | string Solution::longestPalindrome(string s) { 14 | string T = preProcess(s); 15 | const int n = T.length(); 16 | vector P(n); 17 | int C = 0, R = 0; 18 | for (int i = 1; i < n - 1; ++i) { 19 | int i_mirror = 2 * C - i; // equals to i' = C - (i-C) 20 | 21 | P[i] = (R > i) ? min(R - i, P[i_mirror]) : 0; 22 | 23 | // Attempt to expand palindrome centered at i 24 | while (T[i + 1 + P[i]] == T[i - 1 - P[i]]) { 25 | ++P[i]; 26 | } 27 | 28 | // If palindrome centered at i expands the past R, 29 | // adjust center based on expanded palindrome. 30 | if (i + P[i] > R) { 31 | C = i; 32 | R = i + P[i]; 33 | } 34 | } 35 | 36 | // Find the maximum element in P. 37 | int max_i = 0; 38 | for (int i = 1; i < n - 1; ++i) { 39 | if (P[i] > P[max_i]) { 40 | max_i = i; 41 | } 42 | } 43 | 44 | return s.substr((max_i - P[max_i]) / 2, P[max_i]); 45 | } 46 | -------------------------------------------------------------------------------- /C++/maxArea.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxArea(vector &height) { 4 | int end = height.size() - 1, start = 0; 5 | int maxVol = 0; 6 | 7 | while(start < end) 8 | { 9 | maxVol = max(maxVol, (end - start) * min(height[start], height[end])); 10 | 11 | if (height[start] < height[end]) { 12 | start++; 13 | } else { 14 | end--; 15 | } 16 | } 17 | return maxVol; 18 | } 19 | }; 20 | Close 21 | -------------------------------------------------------------------------------- /C++/maxSet.cpp: -------------------------------------------------------------------------------- 1 | vector Solution::maxset(vector &A) { 2 | // Do not write main() function. 3 | // Do not read input, instead use the arguments to the function. 4 | // Do not print the output, instead return values as specified 5 | // Still have a doubt. Checkout www.interviewbit.com/pages/sample_codes/ for more details 6 | int N = A.size(); 7 | 8 | long long mx_sum = 0; 9 | long long cur_sum = 0; 10 | int mx_range_left = -1; 11 | int mx_range_right = -1; 12 | int cur_range_left = 0; 13 | int cur_range_right = 0; 14 | 15 | while(cur_range_right < N) { 16 | if(A[cur_range_right] < 0) { 17 | cur_range_left = cur_range_right + 1; 18 | cur_sum = 0; 19 | } else { 20 | cur_sum += (long long)A[cur_range_right]; 21 | if(cur_sum > mx_sum) { 22 | mx_sum = cur_sum; 23 | mx_range_left = cur_range_left; 24 | mx_range_right = cur_range_right + 1; 25 | } else if(cur_sum == mx_sum) { 26 | if(cur_range_right + 1 - cur_range_left > mx_range_right - mx_range_left) { 27 | mx_range_left = cur_range_left; 28 | mx_range_right = cur_range_right + 1; 29 | } 30 | } 31 | } 32 | cur_range_right++; 33 | } 34 | vector ans; 35 | if(mx_range_left == -1 || mx_range_right == -1) 36 | return ans; 37 | 38 | for(int i = mx_range_left; i < mx_range_right; ++i) 39 | ans.push_back(A[i]); 40 | return ans; 41 | } 42 | -------------------------------------------------------------------------------- /C++/maxSubArray.cpp: -------------------------------------------------------------------------------- 1 | int Solution::maxSubArray(const vector &A) { 2 | // Do not write main() function. 3 | // Do not read input, instead use the arguments to the function. 4 | // Do not print the output, instead return values as specified 5 | // Still have a doubt. Checkout www.interviewbit.com/pages/sample_codes/ for more detai 6 | int max_so_far = A[0]; 7 | int curr_max = A[0]; 8 | 9 | for (int i = 1; i < A.size(); i++) 10 | { 11 | curr_max = max(A[i], curr_max+A[i]); 12 | max_so_far = max(max_so_far, curr_max); 13 | } 14 | return max_so_far; 15 | } 16 | 17 | -------------------------------------------------------------------------------- /C++/mergeIntervals.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for an interval. 3 | * struct Interval { 4 | * int start; 5 | * int end; 6 | * Interval() : start(0), end(0) {} 7 | * Interval(int s, int e) : start(s), end(e) {} 8 | * }; 9 | */ 10 | 11 | /* 12 | *This problem has a lot of corner cases which need to be handled correctly. 13 | *Let us first talk about the approach. 14 | *Given all the intervals, you need to figure out the sequence of intervals which intersect with the given newInterval. 15 | *Lets see how we check if interval 1 (a,b) intersects with interval 2 (c,d): 16 | *Overlap case 17 | * a-------------------b 18 | * c------------------d 19 | *Non overlap case : 20 | * a--------------------b c------------------d 21 | *Note that if max(a,c) > min(b,d), then the intervals do not overlap. Otherwise, they overlap. 22 | *Once we figure out the intervals ( interval[i] to interval[j] ) which overlap with newInterval, note that we can replace all the overlapping intervals with one interval which would be 23 | *(min(interval[i].start, newInterval.start), max(interval[j].end, newInterval.end)). 24 | */ 25 | 26 | 27 | 28 | vector Solution::insert(vector &intervals, Interval newInterval) { 29 | // Do not write main() function. 30 | // Do not read input, instead use the arguments to the function. 31 | // Do not print the output, instead return values as specified 32 | // Still have a doubt. Checkout www.interviewbit.com/pages/sample_codes/ for more details 33 | if(newInterval.start > newInterval.end){ 34 | int temp=newInterval.start; 35 | newInterval.start=newInterval.end; 36 | newInterval.end=temp; 37 | } 38 | 39 | int i=0; 40 | int n=intervals.size(); 41 | int p=-1,q=-1; 42 | for(i=0;i ::iterator it=intervals.begin(); 51 | for(i=0;ival < l2->val) { 11 | head = l1; 12 | l1 = l1->next; 13 | } else { 14 | head = l2; 15 | l2 = l2->next; 16 | } 17 | 18 | ListNode* p = head; // pointer to form new list 19 | 20 | while(l1 && l2){ 21 | if(l1->val < l2->val) { 22 | p->next = l1; 23 | l1 = l1->next; 24 | } else { 25 | p->next = l2; 26 | l2 = l2->next; 27 | } 28 | p = p->next; 29 | } 30 | 31 | // add the rest of the tail, done! 32 | if (l1) { 33 | p->next=l1; 34 | } else { 35 | p->next=l2; 36 | } 37 | 38 | return head; 39 | } 40 | }; 41 | -------------------------------------------------------------------------------- /C++/minStack.cpp: -------------------------------------------------------------------------------- 1 | class MinStack { 2 | private: 3 | stack elementStack; 4 | stack minimumStack; 5 | int minElement = -1; 6 | public: 7 | void push(int x) { 8 | elementStack.push(x); 9 | if(elementStack.size() == 1 || x <= minElement) { 10 | minimumStack.push(x); 11 | minElement = x; 12 | } 13 | } 14 | 15 | void pop() { 16 | if (elementStack.top() == minElement) { 17 | minimumStack.pop(); 18 | if (!minimumStack.empty()) { 19 | minElement = minimumStack.top(); 20 | } else { 21 | minElement = -1; 22 | } 23 | } 24 | elementStack.pop(); 25 | } 26 | 27 | int top() { 28 | if (elementStack.empty()) return -1; 29 | return elementStack.top(); 30 | } 31 | 32 | int getMin() { 33 | return minElement; 34 | } 35 | }; 36 | -------------------------------------------------------------------------------- /C++/numSetBits.cpp: -------------------------------------------------------------------------------- 1 | int Solution::numSetBits(unsigned int A) { 2 | // Do not write main() function. 3 | // Do not read input, instead use the arguments to the function. 4 | // Do not print the output, instead return values as specified 5 | // Still have a doubt. Checkout www.interviewbit.com/pages/sample_codes/ for more details 6 | unsigned int count = 0; 7 | while(A){ 8 | count += A & 1; 9 | A >>= 1; 10 | } 11 | return count; 12 | } 13 | -------------------------------------------------------------------------------- /C++/partition.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | ListNode *partition(ListNode *head, int x) { 4 | 5 | if (!head) return NULL; 6 | ListNode * iterator = head; 7 | 8 | ListNode * start = new ListNode(0); // list of nodes greater than x 9 | ListNode * tail = start; 10 | 11 | ListNode * newHead = new ListNode(0); 12 | newHead -> next = head; 13 | ListNode * pre = newHead; // previous node, we need it for removing 14 | 15 | 16 | while (iterator) { 17 | if (iterator -> val >= x) { 18 | pre -> next = iterator -> next; // remove from our list 19 | tail -> next = iterator; // add to list of nodes greater than x 20 | tail = tail -> next; 21 | iterator = iterator -> next; 22 | tail -> next = NULL; 23 | } 24 | else 25 | pre = iterator, iterator = iterator -> next; 26 | } 27 | pre -> next = start -> next; 28 | return newHead -> next; 29 | } 30 | }; 31 | -------------------------------------------------------------------------------- /C++/pow.cpp: -------------------------------------------------------------------------------- 1 | int pow(int x, int n, int p) { 2 | 3 | //handle base case 4 | if (n == 0) return 1 % p; 5 | 6 | long long ans = 1, base = x; 7 | 8 | while (n > 0) { 9 | // We need (base ** n) % p. 10 | // Now there are 2 cases. 11 | // 1) n is even. Then we can make base = base^2 and n = n / 2. 12 | // 2) n is odd. So we need base * base^(n-1) 13 | if (n % 2 == 1) { 14 | ans = (ans * base) % p; 15 | n--; 16 | } else { 17 | base = (base * base) % p; 18 | n /= 2; 19 | } 20 | } 21 | if (ans < 0) ans = (ans + p) % p; 22 | return ans; 23 | } 24 | 25 | -------------------------------------------------------------------------------- /C++/prevSmaller.cpp: -------------------------------------------------------------------------------- 1 | vector Solution::prevSmaller(vector &A) { 2 | //create answer vector and resize it to input vector 3 | vector ans; 4 | ans.resize(A.size()); 5 | 6 | //init stack 7 | stack st; 8 | 9 | //start iterating through stack 10 | for (int i = 0; i < A.size(); i++) { 11 | //pop off the first element of the stack 12 | while (!st.empty() && st.top() >= A[i]) 13 | st.pop(); 14 | //first value answer vector will always be -1 15 | if (st.empty()) 16 | ans[i] = -1; 17 | else 18 | ans[i] = st.top(); //set the value of a[i] to the lowest current stack value 19 | 20 | //keep pushing elements onto the stack 21 | st.push(A[i]); 22 | } 23 | return ans; 24 | } 25 | -------------------------------------------------------------------------------- /C++/primeSum.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector primesum(int N) { 4 | 5 | // Generate isPrime List less equal than N 6 | vector isPrime(N + 1, true); 7 | isPrime[0] = false; 8 | isPrime[1] = false; 9 | 10 | // Sieve of Erastothenes 11 | for(int i = 2; i <= N; i++) { 12 | if (!isPrime[i]) continue; 13 | if (i > N / i) break; 14 | for (int j = i * i; j <= N; j += i) isPrime[j] = false; 15 | } 16 | 17 | for(int i = 2; i <= N; ++i) { 18 | if(isPrime[i] && isPrime[N - i]) { 19 | vector ans; 20 | ans.push_back(i); 21 | ans.push_back(N - i); 22 | return ans; 23 | } 24 | } 25 | 26 | vector ans; 27 | return ans; 28 | } 29 | }; 30 | -------------------------------------------------------------------------------- /C++/removeNthFromEnd.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | ListNode* removeNthFromEnd(ListNode* head, int n) { 4 | ListNode** t1 = &head, *t2 = head; 5 | for(int i = 1; i < n; ++i) { 6 | t2 = t2->next; 7 | } 8 | while(t2->next != NULL) { 9 | t1 = &((*t1)->next); 10 | t2 = t2->next; 11 | } 12 | *t1 = (*t1)->next; 13 | return head; 14 | } 15 | }; 16 | -------------------------------------------------------------------------------- /C++/reorderList.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) { 4 | if(l1 == NULL) return l2; 5 | if(l2 == NULL) return l1; 6 | 7 | ListNode* head = l1; // head of the list to return 8 | l1 = l1->next; 9 | 10 | ListNode* p = head; // pointer to form new list 11 | // A boolean to track which list we need to extract from. 12 | // We alternate between first and second list. 13 | bool curListNum = true; 14 | 15 | while(l1 && l2){ 16 | if(curListNum == false) { 17 | p->next = l1; 18 | l1 = l1->next; 19 | } else { 20 | p->next = l2; 21 | l2 = l2->next; 22 | } 23 | p = p->next; 24 | curListNum = !curListNum; 25 | } 26 | 27 | // add the rest of the tail, done! 28 | if (l1) { 29 | p->next = l1; 30 | } else { 31 | p->next = l2; 32 | } 33 | 34 | return head; 35 | } 36 | 37 | ListNode *reverseLinkedList(ListNode *head) { 38 | if (head->next == NULL) return head; 39 | ListNode *cur = head, *nextNode = head->next, *tmp; 40 | 41 | while (nextNode != NULL) { 42 | tmp = nextNode->next; 43 | nextNode->next = cur; 44 | cur = nextNode; 45 | nextNode = tmp; 46 | } 47 | 48 | head->next = nextNode; 49 | return cur; 50 | } 51 | 52 | ListNode* reorderList(ListNode *head) { 53 | if(head == NULL || head->next == NULL || head->next->next==NULL) 54 | return head; 55 | 56 | //find the middle of the list, and split into two lists. 57 | ListNode *slow = head,*fast = head; 58 | while(slow != NULL && fast != NULL && fast->next != NULL && fast->next->next != NULL){ 59 | slow = slow->next; 60 | fast = fast->next->next; 61 | } 62 | 63 | ListNode *mid = slow->next; 64 | slow->next = NULL; 65 | 66 | //reverse from the middle to the end 67 | ListNode* secondHalfReversed = reverseLinkedList(mid); 68 | 69 | //merge these two list 70 | return head = mergeTwoLists(head, secondHalfReversed); 71 | } 72 | }; 73 | -------------------------------------------------------------------------------- /C++/repeatedNum.cpp: -------------------------------------------------------------------------------- 1 | int Solution::repeatedNumber(const vector &A) { 2 | // Do not write main() function. 3 | // Do not read input, instead use the arguments to the function. 4 | // Do not print the output, instead return values as specified 5 | // Still have a doubt. Checkout www.interviewbit.com/pages/sample_codes/ for more details 6 | int slow = A[0]; 7 | int fast = A[A[0]]; 8 | while (slow != fast) { 9 | slow = A[slow]; 10 | fast = A[A[fast]]; 11 | } 12 | 13 | fast = 0; 14 | while (slow != fast) { 15 | slow = A[slow]; 16 | fast = A[fast]; 17 | } 18 | return slow; 19 | } 20 | -------------------------------------------------------------------------------- /C++/reverse.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int reverse(int x) { 4 | // solution without using strings 5 | int rev = 0, sign = 1, digit; 6 | if (x < 0) { 7 | sign = -1; 8 | x *= -1; 9 | } 10 | while (x > 0) { 11 | digit = x%10; 12 | // check for overflow here 13 | if (rev > (INT_MAX / 10) || (rev == (INT_MAX / 10) && digit > (INT_MAX % 10))) { 14 | return 0; 15 | } 16 | rev = rev * 10 + digit; 17 | x/=10; 18 | } 19 | rev *= sign; 20 | return rev; 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /C++/reverseBetween.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | 4 | // Reverses the linkedList which starts from head, and extends to size nodes. 5 | // Returns the end node. 6 | // Also sets the head->next as endNode->next. 7 | ListNode *reverseLinkedList(ListNode *head, int size) { 8 | if (size <= 1) return head; 9 | ListNode *cur = head, *nextNode = head->next, *tmp; 10 | 11 | for (int i = 0; i < (size - 1); i++) { 12 | tmp = nextNode->next; 13 | nextNode->next = cur; 14 | cur = nextNode; 15 | nextNode = tmp; 16 | } 17 | 18 | head->next = nextNode; 19 | return cur; 20 | } 21 | 22 | ListNode *reverseBetween(ListNode *head, int m, int n) { 23 | // Introduce dummyhead to not handle corner cases. 24 | ListNode* dummyHead = new ListNode(0); 25 | dummyHead->next = head; 26 | 27 | // Figure out the start node of the sublist we are going to reverse 28 | ListNode* prev = dummyHead; 29 | ListNode* cur = head; 30 | int index = 1; 31 | while (index < m) { 32 | prev = cur; 33 | cur = cur->next; 34 | index++; 35 | } 36 | 37 | // At this point, we have start of sublist in cur, prev of startSubList in prev. 38 | // Lets reverse the sublist now. 39 | ListNode* endSubList = reverseLinkedList(cur, n - m + 1); 40 | prev->next = endSubList; 41 | 42 | return dummyHead->next; 43 | } 44 | }; 45 | -------------------------------------------------------------------------------- /C++/roman2int.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int romanToInt(string s) { 4 | int num = 0; 5 | int size = s.size(); 6 | 7 | for (int i = 0; i < size; i++) { 8 | // Does lesser value precede higher value ? 9 | if (i < (size - 1) && romanCharToInt(s[i]) < romanCharToInt(s[i + 1])) { 10 | num -= romanCharToInt(s[i]); 11 | } else { 12 | num += romanCharToInt(s[i]); 13 | } 14 | } 15 | return num; 16 | } 17 | 18 | int romanCharToInt(char c) { 19 | switch (c) { 20 | case 'I': return 1; 21 | case 'V': return 5; 22 | case 'X': return 10; 23 | case 'L': return 50; 24 | case 'C': return 100; 25 | case 'D': return 500; 26 | case 'M': return 1000; 27 | default: return 0; 28 | } 29 | } 30 | }; 31 | -------------------------------------------------------------------------------- /C++/rotate.cpp: -------------------------------------------------------------------------------- 1 | void Solution::rotate(vector > &matrix) { 2 | 3 | int len = matrix.size(); 4 | for (int i = 0; i < len / 2; i++) { 5 | for (int j = i; j < len - i - 1; j++) { 6 | int tmp = matrix[i][j]; 7 | matrix[i][j] = matrix[len - j - 1][i]; 8 | matrix[len - j - 1][i] = matrix[len - i - 1][len - j - 1]; 9 | matrix[len - i - 1][len - j - 1] = matrix[j][len - i - 1]; 10 | matrix[j][len - i - 1] = tmp; 11 | } 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /C++/rotateRight.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | ListNode *rotateRight(ListNode *head, int k) { 4 | if (head == NULL || head->next == NULL) return head; 5 | 6 | ListNode* dummy = new ListNode(0); 7 | dummy->next = head; 8 | 9 | ListNode *fast = dummy, *slow = dummy; 10 | 11 | int sizeOfList = 0; 12 | while (fast->next != NULL) { 13 | fast = fast->next; 14 | sizeOfList++; 15 | } 16 | 17 | int firstNodePos = sizeOfList - (k % sizeOfList); 18 | for (int i = 0; i < firstNodePos; i++) { 19 | slow = slow->next; 20 | } 21 | 22 | fast->next = dummy->next; 23 | dummy->next = slow->next; 24 | slow->next = NULL; 25 | 26 | return dummy->next; 27 | } 28 | }; 29 | -------------------------------------------------------------------------------- /C++/rotatedsearch.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | // returns the index. 4 | int findMin(const vector &A, int start, int end) { 5 | if (start > end) return -1; 6 | if (start == end) { 7 | return start; 8 | } 9 | int mid = (start + end) / 2; 10 | if (A[mid] < A[end]) { 11 | return findMin(A, start, mid); 12 | } else if (A[mid] > A[end]) { 13 | return findMin(A, mid + 1, end); 14 | } else { 15 | // should not come here 16 | int index1 = findMin(A,start, mid); 17 | int index2 = findMin(A, mid + 1, end); 18 | if (index1 != -1 && index2 != -1) { 19 | if (A[index1] < A[index2]) return index1; 20 | return index2; 21 | } else if (index1 != -1) return index1; 22 | else return index2; 23 | } 24 | } 25 | 26 | int binarySearch(const vector &A, int start, int end, int target) { 27 | if (start > end) return -1; 28 | if (start == end) { 29 | if (A[start] == target) 30 | return start; 31 | return -1; 32 | } 33 | int mid = (start + end) / 2; 34 | if (A[mid] < target) { 35 | return binarySearch(A, mid + 1, end, target); 36 | } else return binarySearch(A, start, mid, target); 37 | } 38 | 39 | int search(const vector &A, int target) { 40 | int n = A.size(); 41 | int index = findMin(A, 0, n - 1); 42 | int index1 = binarySearch(A, 0, index, target); 43 | if (index1 != -1) return index1; 44 | return binarySearch(A, index, n - 1, target); 45 | } 46 | }; 47 | -------------------------------------------------------------------------------- /C++/searchInsert.cpp: -------------------------------------------------------------------------------- 1 | int Solution::searchInsert(vector &A, int B) { 2 | // Do not write main() function. 3 | // Do not read input, instead use the arguments to the function. 4 | // Do not print the output, instead return values as specified 5 | // Still have a doubt. Checkout www.interviewbit.com/pages/sample_codes/ for more details 6 | if(A.empty() || B <= A[0]) 7 | return 0; 8 | 9 | int low = 0, hi = A.size() - 1; 10 | 11 | while(low <= hi){ 12 | int mid = low + (hi - low) / 2; 13 | 14 | if(B == A[mid]) 15 | return mid; 16 | else if (B > A[mid]) 17 | low = mid + 1; 18 | else 19 | hi = mid - 1; 20 | } 21 | return low; 22 | } 23 | -------------------------------------------------------------------------------- /C++/searchMatrix.cpp: -------------------------------------------------------------------------------- 1 | bool searchMatrix(vector > &matrix, int target) { 2 | int n = matrix.size(); 3 | int m = matrix[0].size(); 4 | int l = 0, r = m * n - 1; 5 | while (l != r){ 6 | int mid = (l + r - 1) >> 1; 7 | if (matrix[mid / m][mid % m] < target) 8 | l = mid + 1; 9 | else 10 | r = mid; 11 | } 12 | return matrix[r / m][r % m] == target; 13 | } 14 | -------------------------------------------------------------------------------- /C++/setMatrixZeros.cpp: -------------------------------------------------------------------------------- 1 | void Solution::setZeroes(vector > &matrix) { 2 | // Start typing your C/C++ solution below 3 | // DO NOT write int main() function 4 | int row = matrix.size(); 5 | if (row==0){return;} 6 | int col = matrix[0].size(); 7 | if (col==0){return;} 8 | 9 | bool fc0=false; 10 | bool fr0=false; 11 | 12 | for (int i=0;i &A) { 2 | // Do not write main() function. 3 | // Do not read input, instead use the arguments to the function. 4 | // Do not print the output, instead return values as specified 5 | // Still have a doubt. Checkout www.interviewbit.com/pages/sample_codes/ for more details 6 | return accumulate(A.cbegin(), A.cend(), 7 | 0, std::bit_xor()); 8 | } 9 | -------------------------------------------------------------------------------- /C++/singleNumberii.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int singleNumber(const vector &A) { 4 | int result = 0; 5 | for (int i = 0; i < A.size(); i++) { 6 | result ^= A[i]; 7 | } 8 | return result; 9 | } 10 | }; 11 | -------------------------------------------------------------------------------- /C++/sqrt.cpp: -------------------------------------------------------------------------------- 1 | int Solution::sqrt(int A) { 2 | //base cases 3 | if(A == 0 || A == 1) 4 | return A; 5 | 6 | //algo 7 | long long start = 1, end = A, ans; 8 | while(start <= end){ 9 | long long mid = (start + end) >> 1; 10 | 11 | //case 1: if perfect square 12 | if(mid * mid == A) 13 | return (int)mid; 14 | //case 2: increment right 15 | if(mid * mid < A){ 16 | start = mid + 1; 17 | ans = mid; 18 | } 19 | //case 3: increment left 20 | else 21 | end = mid - 1; 22 | } 23 | return (int)ans; 24 | } 25 | 26 | -------------------------------------------------------------------------------- /C++/substr.cpp: -------------------------------------------------------------------------------- 1 | int Solution::strStr(const string &haystack, const string &needle) { 2 | // Do not write main() function. 3 | // Do not read input, instead use the arguments to the function. 4 | // Do not print the output, instead return values as specified 5 | if (needle.empty()) { 6 | return 0; 7 | } 8 | 9 | for (int i = 0; i + needle.length() < haystack.length() + 1; ++i) { 10 | if (haystack.substr(i, needle.length()) == needle) { 11 | return i; 12 | } 13 | } 14 | return -1; 15 | } 16 | -------------------------------------------------------------------------------- /C++/swapColor.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | void sortColors(int A[], int n) { 4 | int n = A.size(); 5 | int k = n - 1; 6 | int i = 0; 7 | for (; i < n; ++i) 8 | { 9 | if (A[i] != 0) 10 | { 11 | break; 12 | } 13 | } 14 | 15 | int j = i; 16 | for (; i <= k; ++i) 17 | { 18 | if (A[i] == 0) 19 | { 20 | swap(A[j++], A[i]); 21 | } 22 | else if (A[i] == 2) 23 | { 24 | swap(A[i--], A[k--]); 25 | } 26 | } 27 | } 28 | }; 29 | -------------------------------------------------------------------------------- /C++/titleToNumber.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int titleToNumber(string s) { 4 | int result = 0; 5 | for (int i = 0; i < s.size(); i++) { 6 | result = result * 26 + (s[i] - 'A' + 1); 7 | } 8 | return result; 9 | } 10 | }; 11 | -------------------------------------------------------------------------------- /C++/trailingZeros.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int trailingZeroes(int n) { 4 | int sum = 0; 5 | while (n / 5 > 0) { 6 | sum += (n / 5); 7 | n /= 5; 8 | } 9 | return sum; 10 | } 11 | }; 12 | -------------------------------------------------------------------------------- /C++/uniquePaths.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int uniquePaths(int m, int n) { 4 | // m+n-2 C n-1 = (m+n-2)! / (n-1)! (m-1)! 5 | long long ans = 1; 6 | for (int i = n; i < (m + n - 1); i++) { 7 | ans *= i; 8 | ans /= (i - n + 1); 9 | } 10 | return (int)ans; 11 | } 12 | }; 13 | -------------------------------------------------------------------------------- /C++/wave.cpp: -------------------------------------------------------------------------------- 1 | void swap(int& a,int &b){ 2 | int c=a; 3 | a=b; 4 | b=c; 5 | } 6 | 7 | vector Solution::wave(vector &A) { 8 | // Do not write main() function. 9 | // Do not read input, instead use the arguments to the function. 10 | // Do not print the output, instead return values as specified 11 | // Still have a doubt. Checkout www.interviewbit.com/pages/sample_codes/ for more details 12 | int n = A.size(); 13 | 14 | sort(A.begin(), A.begin()+n); 15 | for(int i = 0; i < n-1; i += 2){ 16 | swap(A[i],A[i+1]); 17 | } 18 | return A; 19 | } 20 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | {one line to give the program's name and a brief idea of what it does.} 635 | Copyright (C) {year} {name of author} 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | {project} Copyright (C) {year} {fullname} 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /Python/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Alex-Keyes/InterviewBit/d0a02b1170c1391d07a8962e8ae1935e2d79ebb2/Python/__init__.py -------------------------------------------------------------------------------- /Python/addTwoNumbers.py: -------------------------------------------------------------------------------- 1 | # Definition for singly-linked list. 2 | # class ListNode: 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.next = None 6 | 7 | class Solution: 8 | # @param A : head node of linked list 9 | # @param B : head node of linked list 10 | # @return the head node in the linked list 11 | def addTwoNumbers(self, A, B): 12 | a, b = A, B 13 | head = ListNode(0) 14 | cur_sum = head 15 | while a != None or b != None or cur_sum.val > 9: 16 | carry = cur_sum.val / 10 17 | cur_sum.val %= 10 18 | a_val = 0 if a == None else a.val 19 | b_val = 0 if b == None else b.val 20 | next_val = a_val + b_val + carry 21 | cur_sum.next = ListNode(next_val) 22 | cur_sum = cur_sum.next 23 | a = None if a == None else a.next 24 | b = None if b == None else b.next 25 | return head.next 26 | -------------------------------------------------------------------------------- /Python/addone.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | # @param A : list of integers 3 | # @return a list of integers 4 | def plusOne(self, A): 5 | while (A[0] == 0) and len(A) > 1: 6 | del (A[0]) 7 | if A[0] == 0 and len(A) == 1: 8 | A[0] = 1 9 | return A 10 | i = len(A) - 1 11 | carry = 1 12 | while True: 13 | value = A[i] + carry 14 | if value >= 10: 15 | A[i] = value % 10 16 | carry = value // 10 17 | else: 18 | A[i] = value 19 | break 20 | if i == 0: 21 | A.insert(0, carry) 22 | break 23 | i -= 1 24 | return A 25 | -------------------------------------------------------------------------------- /Python/arrange.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | # @param A : list of integers 3 | def arrange(self, A): 4 | n = len(A) 5 | B = [0]*n 6 | for i in range(n): 7 | B[i] = A[i] 8 | for i in range(n): 9 | A[i] = B[B[i]] 10 | 11 | -------------------------------------------------------------------------------- /Python/convertToTitle.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | # @param A : integer 3 | # @return a strings 4 | def convertToTitle(self, A): 5 | ret = '' 6 | while A != 0: 7 | A = A-1 8 | temp = A%26 9 | A /= 26 10 | ret += chr(temp+ord('A')) 11 | return ret[::-1] 12 | -------------------------------------------------------------------------------- /Python/detectCycle.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | # @param A : head node of linked list 3 | # @return the head node in the linked list 4 | def detectCycle(self, A): 5 | seen = set() 6 | while A: 7 | if A.val in seen: 8 | return A 9 | else: 10 | seen.add(A.val) 11 | A = A.next 12 | -------------------------------------------------------------------------------- /Python/flip.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | # @param A : string 3 | # @return a list of integers 4 | def flip(self, A): 5 | max_diff = 0 6 | diff = 0 7 | ones = 0 8 | start = 0 9 | ans = None 10 | 11 | for i, a in enumerate(A): 12 | diff += (1 if a is '0' else -1) 13 | 14 | if diff < 0: 15 | diff = 0 16 | start = i + 1 17 | continue 18 | 19 | if diff > max_diff: 20 | max_diff = diff 21 | ans = [start, i] 22 | 23 | if ans is None: 24 | return [] 25 | return map(lambda x: x + 1, ans) 26 | -------------------------------------------------------------------------------- /Python/gcd.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | # @param A : integer 3 | # @param B : integer 4 | # @return an integer 5 | def gcd(self, a, b): 6 | if (b == 0): 7 | return a 8 | else: 9 | return self.gcd(b, a%b) 10 | -------------------------------------------------------------------------------- /Python/generateMatrix.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | # @param A : integer 3 | # @return a list of list of integers 4 | def generateMatrix(self, A): 5 | n = A 6 | ret = [[0]*n] 7 | for i in range(n-1): 8 | ret.append([0]*n) 9 | 10 | T = 0 11 | B = n-1 12 | L = 0 13 | R = n-1 14 | direction = 0 15 | num = 1 16 | while T <=B and L <=R: 17 | if direction == 0: 18 | for i in range(L,R+1): 19 | ret[T][i] = num 20 | num += 1 21 | T += 1 22 | direction = 1 23 | elif direction == 1: 24 | for i in range(T,B+1): 25 | ret[i][R] = num 26 | num += 1 27 | R -= 1 28 | direction = 2 29 | elif direction == 2: 30 | for i in range(R,L-1,-1): 31 | ret[B][i] = num 32 | num += 1 33 | B -= 1 34 | direction = 3 35 | else: 36 | for i in range(B,T-1,-1): 37 | ret[i][L] = num 38 | num += 1 39 | L += 1 40 | direction = 0 41 | return ret 42 | -------------------------------------------------------------------------------- /Python/generatePascal.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | # @param A : integer 3 | # @return a list of list of integers 4 | def generate(self, numRows): 5 | result = [] 6 | for i in xrange(numRows): 7 | result.append([]) 8 | for j in xrange(i + 1): 9 | if j in (0, i): 10 | result[i].append(1) 11 | else: 12 | result[i].append(result[i - 1][j - 1] + result[i - 1][j]) 13 | return result 14 | -------------------------------------------------------------------------------- /Python/getRow.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | # @param A : integer 3 | # @return a list of integers 4 | def getRow(self, A): 5 | A += 1 6 | ret = [] 7 | if A == 0: 8 | return ret 9 | ret = [[1]] 10 | for i in range(2,A+1): 11 | ret.append([0]*i) 12 | ret[i-1][0] = 1 13 | ret[i-1][-1] = 1 14 | for j in range(1,i-1): 15 | ret[i-1][j] = ret[i-2][j-1]+ret[i-2][j] 16 | return ret[-1] 17 | -------------------------------------------------------------------------------- /Python/isPalindrome.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | # @param A : integer 3 | # @return an integer 4 | def isPalindrome(self, A): 5 | A = str(A) 6 | for i in range(len(A)/2+1): 7 | if A[i] != A[-(i+1)]: 8 | return 0 9 | return 1 10 | -------------------------------------------------------------------------------- /Python/isPower.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | # @param A : integer 3 | # @return a boolean 4 | def isPower(self, N): 5 | if N == 0: 6 | return False 7 | if N == 1: 8 | return True 9 | for p in xrange(2,33): 10 | for A in xrange(2, int(N**(1.0 / p)) + 2): 11 | if A**p == N: 12 | return True 13 | return False 14 | -------------------------------------------------------------------------------- /Python/maxSet.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | # @param A : list of integers 3 | # @return a list of integers 4 | def maxset(self, A): 5 | max_ending_here = 0 6 | start_ending_here = 0 7 | end_ending_here = 0 8 | max_so_far = 0 9 | start_so_far = 0 10 | end_so_far = 0 11 | 12 | allNegative = True 13 | n = len(A) 14 | if n == 0: 15 | return [] 16 | for i in range(n): 17 | if A[i] >= 0: 18 | allNegative = False 19 | if max_ending_here + A[i] >= max_ending_here: 20 | max_ending_here += A[i] 21 | end_ending_here = i 22 | else: 23 | if max_so_far < max_ending_here: 24 | max_so_far = max_ending_here 25 | start_so_far = start_ending_here 26 | end_so_far = end_ending_here 27 | elif max_so_far <= max_ending_here: 28 | if end_ending_here - start_ending_here > end_so_far - start_so_far: 29 | max_so_far = max_ending_here 30 | start_so_far = start_ending_here 31 | end_so_far = end_ending_here 32 | max_ending_here = 0 33 | start_ending_here = i+1 34 | end_ending_here = 0 35 | 36 | if max_so_far < max_ending_here: 37 | max_so_far = max_ending_here 38 | start_so_far = start_ending_here 39 | end_so_far = end_ending_here 40 | elif max_so_far <= max_ending_here: 41 | if end_ending_here - start_ending_here > end_so_far - start_so_far: 42 | max_so_far = max_ending_here 43 | start_so_far = start_ending_here 44 | end_so_far = end_ending_here 45 | if allNegative: 46 | return [] 47 | else: 48 | return A[start_so_far:end_so_far+1] 49 | -------------------------------------------------------------------------------- /Python/nextPermutation.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | # @param A : list of integers 3 | # @return the same list of integer after modification 4 | def nextPermutation(self, A): 5 | if len(A) == 1: 6 | return A 7 | 8 | if len(A) == 2: 9 | self.swap(A, 0, 1) 10 | return A 11 | 12 | for i in xrange(len(A) - 2, 0, -1): 13 | 14 | if A[i - 1] >= A[i] >= A[i + 1] and i != 1: 15 | continue 16 | 17 | if A[i - 1] >= A[i] >= A[i + 1] and i == 1: 18 | for j in xrange(len(A) / 2): 19 | self.swap(A, j, len(A) - 1 - j) 20 | return A 21 | 22 | if (A[i - 1] >= A[i] or A[i - 1] <= A[i]) and A[i] <= A[i + 1]: 23 | self.swap(A, i, i + 1) 24 | return A 25 | 26 | if A[i] >= A[i - 1] and A[i] >= A[i + 1] and A[i - 1] >= A[i + 1]: 27 | temp = sorted(A[i:]) 28 | for j in xrange(i, len(A)): 29 | A[j] = temp[j - j] 30 | temp.pop(j - j) 31 | low = A[i - 1] 32 | for j in xrange(i, len(A)): 33 | if A[j] > low: 34 | self.swap(A, j, i - 1) 35 | break 36 | return A 37 | 38 | if A[i] >= A[i - 1] and A[i] >= A[i + 1] and A[i - 1] <= A[i + 1]: 39 | temp = sorted(A[i:]) 40 | for j in xrange(i, len(A)): 41 | A[j] = temp[j - j] 42 | temp.pop(j - j) 43 | low = A[i - 1] 44 | for j in xrange(i, len(A)): 45 | if A[j] > low: 46 | self.swap(A, j, i - 1) 47 | break 48 | return A 49 | 50 | def swap(self, A, index_i, index_j): 51 | temp = A[index_i] 52 | A[index_i] = A[index_j] 53 | A[index_j] = temp 54 | 55 | 56 | -------------------------------------------------------------------------------- /Python/partition.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | # @param {ListNode} head 3 | # @param {integer} x 4 | # @return {ListNode} 5 | def partition(self, head, x): 6 | if not head: 7 | return None 8 | 9 | less, greaterEqual = ListNode(0), ListNode(0) 10 | tempLess, tempGreaterEqual, temp = less, greaterEqual, head 11 | while temp: 12 | if temp.val < x: 13 | tempLess.next = temp 14 | tempLess = tempLess.next 15 | else: 16 | tempGreaterEqual.next = temp 17 | tempGreaterEqual = tempGreaterEqual.next 18 | 19 | cur = temp 20 | temp = temp.next 21 | cur.next = None 22 | 23 | tempLess.next = greaterEqual.next 24 | return less.next 25 | -------------------------------------------------------------------------------- /Python/primeSum.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def primesum(self, n): 3 | for i in xrange(2, n): 4 | if self.is_prime(i) and self.is_prime(n - i): 5 | return i, n - i 6 | 7 | def is_prime(self, n): 8 | if n < 2: 9 | return False 10 | 11 | for i in xrange(2, int(n**0.5) + 1): 12 | if n % i == 0: 13 | return False 14 | 15 | return True 16 | -------------------------------------------------------------------------------- /Python/reorderList.py: -------------------------------------------------------------------------------- 1 | # Definition for singly-linked list. 2 | # class ListNode: 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.next = None 6 | 7 | class Solution: 8 | # @param A : head node of linked list 9 | # @return the head node in the linked list 10 | def reorderList(self, A): 11 | arr = [] 12 | ca = A 13 | alen = 0 14 | while ca: 15 | arr.append(ca) 16 | alen += 1 17 | ca = ca.next 18 | cn = arr[0] 19 | for i in xrange(1, alen): 20 | if i%2 == 0: 21 | cn.next = arr[i/2] 22 | cn = cn.next 23 | if i == alen - 1: 24 | cn.next = None 25 | else: 26 | cn.next = arr[alen - i/2 - 1] 27 | cn = cn.next 28 | if i == alen - 1: 29 | cn.next = None 30 | return A 31 | -------------------------------------------------------------------------------- /Python/reverse.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | # @param A : integer 3 | # @return an integer 4 | def reverse(self, A): 5 | A = str(A) 6 | if A[0] == '-': 7 | A = '-'+A[1:][::-1] 8 | else: 9 | A = A[::-1] 10 | A = int(A) 11 | if A > 2**31 or A < -2**31: 12 | return 0 13 | return A 14 | -------------------------------------------------------------------------------- /Python/titleToNumber.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | # @param A : string 3 | # @return an integer 4 | def titleToNumber(self, A): 5 | n = len(A) 6 | A = A[::-1] 7 | ret = 0 8 | for i in range(n): 9 | ret += (26**(i))*(ord(A[i])-ord('A')+1) 10 | return ret 11 | -------------------------------------------------------------------------------- /Python/trailingZeros.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | # @param A : integer 3 | # @return an integer 4 | def trailingZeroes(self, n): 5 | i = 1 6 | result = 0 7 | while n >= i: 8 | i *= 5 9 | result += n/i # (taking floor, just like Python or Java does) 10 | return result 11 | -------------------------------------------------------------------------------- /Python/uniquePaths.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | # @param A : integer 3 | # @param B : integer 4 | # @return an integer 5 | def uniquePaths(self, A, B): 6 | return math.factorial(A+B-2)/(math.factorial(A-1)*math.factorial(B-1)) 7 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |

2 | ib-logo-square.png 3 |

4 | 5 | # InterviewBit Solutions 6 | 7 | ![languages-Python%20&%20C++-orange.svg](https://img.shields.io/badge/languages-Python%20&%20C++-orange.svg) [![License-GNU-red.svg](https://img.shields.io/badge/License-GNU-red.svg)](https://img.shields.io/badge/License-GNU-red.svg) [![codebeat-A-brightgreen.svg](https://img.shields.io/badge/codebeat-A-brightgreen.svg)](https://codebeat.co/projects/github-com-alex-keyes-interviewbit) 8 | 9 | This is a repository of solutions to all problems I've solved on InterviewBit. I am not quite sure exactly how many problems there are on the website, but I'll be updating this with every problem I solve. Please issue a pull request if you think you have a better solution or something I could improve upon. 10 | 11 | # Topics 12 | 13 | * [Time Complexity](https://github.com/Alex-Keyes/InterviewBit#Time+Complexity) 14 | * [Arrays](https://github.com/Alex-Keyes/InterviewBit#Arrays) 15 | * [Math](https://github.com/Alex-Keyes/InterviewBit#Math) 16 | * [Binary Search](https://github.com/Alex-Keyes/InterviewBit#Binary+Search) 17 | * [Linked Lists](https://github.com/Alex-Keyes/InterviewBit#Linked+Lists) 18 | * [Stack and Queue](https://github.com/Alex-Keyes/InterviewBit#Stack+and+Queue) 19 | 20 | # Problem Lists 21 | ## [Time Complexity](https://www.interviewbit.com/courses/programming/topics/time-complexity/) 22 | [Answers](https://github.com/Alex-Keyes/InterviewBit/blob/master/timeComplexity.md) 23 | 24 | 25 | 26 | ## [Arrays](https://www.interviewbit.com/courses/programming/topics/arrays) 27 | | SubTopic | Title | Solution | Notes | 28 | | --- | --- | --- | --- | 29 | | Simulation Array | [Pascal Triangle Rows](https://www.interviewbit.com/problems/pascal-triangle-rows/) | [cpp](./C++/generatePascal.cpp) [python](./Python/generatePascal.py) | 30 | | Array math | [Min Steps in Infinite Grid](https://www.interviewbit.com/problems/min-steps-in-infinite-grid/) | [C++](/C++/coverPoints.cpp) | Simpler Than I originally thought. | 31 | | Array math | [Max Sum Contiguous Subarray](https://www.interviewbit.com/problems/max-sum-contiguous-subarray/) | [C++](/C++/maxSubArray.cpp) | | 32 | | Array math | [Add One To Number](https://www.interviewbit.com/problems/add-one-to-number/) | [Python](/Python/addone.py) | | 33 | | Array math | [Repeat and Missing Number Array](https://www.interviewbit.com/problems/repeat-and-missing-number-array/) | [Python](/Python/repeatedNumber.py) | | 34 | | Array math | [Flip](https://www.interviewbit.com/problems/flip/) | [Python](/Python/flip.py) | | 35 | | Simulation array | [Max Non Negative SubArray](https://www.interviewbit.com/problems/max-non-negative-subarray/) | [C++](/C++/maxSet.cpp) [Python](file:Python/maxSet.py) | | 36 | | Simulation array | [Kth Row of Pascal's Triangle](https://www.interviewbit.com/problems/kth-row-of-pascals-triangle/) | [Python](/Python/getRow.py) | | 37 | | Simulation array | [Pascal Triangle Rows](https://www.interviewbit.com/problems/pascal-triangle-rows/) | [Python](/Python/generatePascal.py) | | 38 | | Simulation array | [Spiral Order Matrix II](https://www.interviewbit.com/problems/spiral-order-matrix-ii/) | [C++](/C++/generateMatrix.cpp) [Python](/Python/generateMatrix.py) | | 39 | | Simulation array | [Anti Diagonals](https://www.interviewbit.com/problems/anti-diagonals/) | [C++](/C++/diagonal.cpp) | | 40 | | Arrangement | [Rotate Matrix](https://www.interviewbit.com/problems/rotate-matrix/) | [C++](/C++/rotate.cpp) | | 41 | | Arrangement | [Largest Number](https://www.interviewbit.com/problems/largest-number/) | [C++](C++/largestNum.cpp) | | 42 | | Arrangement | [Next Permutation](https://www.interviewbit.com/problems/next-permutation/) | [Python](/Python/nextPermutation.py) | | 43 | | Bucketing or sorting | Hotel Bookings Possible | | | 44 | | Bucketing or sorting | [Wave Array](https://www.interviewbit.com/problems/wave-array/) | [C++](/C++/wave.cpp) | | 45 | | Bucketing or sorting | [Largest Number]([https://www.interviewbit.com/problems/largest-number/) | [C++](/C++/largestNum.cpp) | | 46 | | Bucketing or sorting | Max Distance | | | 47 | | Bucketing or sorting | Maximum Consecutive Gap | | | 48 | | Bucketing or sorting | [Find Duplicate in Array](https://www.interviewbit.com/problems/find-duplicate-in-array/) | [C++](/C++/repeatedNum.cpp) | | 49 | | Value ranges | [Merge Intervals](https://www.interviewbit.com/problems/merge-intervals/) | [C++](/C++/mergeIntervals.cpp) | | 50 | | Value ranges | Merge Overlapping Intervals | | | 51 | | Space recycle | [Set Matrix Zeros](https://www.interviewbit.com/problems/set-matrix-zeros/) | [C++](/C++/setMatrixZeros.cpp) | | 52 | | Space recycle | First Missing Integer | | | 53 | | Missing / repeated number | First Missing Integer | | | 54 | | Missing / repeated number | Repeat and Missing Number Array | | | 55 | | Missing / repeated number | Find Duplicate in Array | | | 56 | | Missing / repeated number | N/3 Repeat Number | | | 57 | ## [Math](http://interviewbit.com/courses/programming/topics/math/) 58 | ## [Binary Search](https://www.interviewbit.com/courses/programming/topics/binary-search/) 59 | ## [Stack and Queue](https://www.interviewbit.com/courses/programming/topics/stacks-and-queues/) 60 | ## [Linked Lists](https://www.interviewbit.com/courses/programming/topics/linked-lists/) 61 | -------------------------------------------------------------------------------- /README.org: -------------------------------------------------------------------------------- 1 | [[file:img/ib-logo-square.png]] 2 | * InterviewBit Solutions 3 | 4 | [[https://img.shields.io/badge/languages-Python & C++-orange.svg]] [[https://img.shields.io/badge/License-GNU-red.svg][https://img.shields.io/badge/License-GNU-red.svg]] [[https://codebeat.co/projects/github-com-alex-keyes-interviewbit][https://img.shields.io/badge/codebeat-A-brightgreen.svg]] [[https://github.com/syl20bnr/spacemacs][file:https://cdn.rawgit.com/syl20bnr/spacemacs/442d025779da2f62fc86c2082703697714db6514/assets/spacemacs-badge.svg]] 5 | 6 | This is a repository of solutions to all problems I've solved on InterviewBit. 7 | I am not quite sure exactly how many problems there are on the website, but I'll be updating this with every problem I solve. 8 | Please issue a pull request if you think you have a better solution or something I could improve upon. 9 | 10 | * Topics 11 | - [[Arrays][Arrays]] 12 | - [[Math][Math]] 13 | - [[Binary Search][Binary Search]] 14 | - [[String][String]] 15 | - [[Bit Manipulation][Bit Manipulationpri]] 16 | - [[Two-Pointers][Two-Pointers]] 17 | - [[Linked Lists][Linked Lists]] 18 | - [[Stack and Queue][Stack and Queue]] 19 | 20 | * Problem Lists 21 | ** [[https://www.interviewbit.com/courses/programming/topics/arrays][Arrays]] 22 | | SubTopic | Title | Solution | Notes | 23 | | Array math | [[https://www.interviewbit.com/problems/min-steps-in-infinite-grid/][Min Steps in Infinite Grid]] | [[/C++/coverPoints.cpp][C++]] | Simpler Than I originally thought. | 24 | | Array math | [[https://www.interviewbit.com/problems/max-sum-contiguous-subarray/][Max Sum Contiguous Subarray]] | [[/C++/maxSubArray.cpp][C++]] | | 25 | | Array math | Add One To Number | | | 26 | | Array math | Repeat and Missing Number Array | | | 27 | | Array math | Flip | | | 28 | | Simulation array | [[https://www.interviewbit.com/problems/max-non-negative-subarray/][Max Non Negative SubArray]] | [[/C++/maxSet.cpp][C++]] [[file:Python/maxSet.py][Python]] | | 29 | | Simulation array | Kth Row of Pascal's Triangle | | | 30 | | Simulation array | [[https://www.interviewbit.com/problems/pascal-triangle-rows/][Pascal Triangle Rows]] | [[/Python/generatePascal.py][Python]] | | 31 | | Simulation array | [[https://www.interviewbit.com/problems/spiral-order-matrix-ii/][Spiral Order Matrix II]] | [[/C++/generateMatrix.cpp][C++]] [[/Python/generateMatrix.py][Python]] | | 32 | | Simulation array | [[https://www.interviewbit.com/problems/anti-diagonals/][Anti Diagonals]] | [[/C++/diagonal.cpp][C++]] | | 33 | | Arrangement | [[https://www.interviewbit.com/problems/rotate-matrix/][Rotate Matrix]] | [[/C++/rotate.cpp][C++]] | | 34 | | Arrangement | [[https://www.interviewbit.com/problems/largest-number/][Largest Number]] | [[/C++/largestNum.cpp][C++]] | | 35 | | Arrangement | Next Permutation | | | 36 | | Bucketing or sorting | Hotel Bookings Possible | | | 37 | | Bucketing or sorting | [[https://www.interviewbit.com/problems/wave-array/][Wave Array]] | [[/C++/wave.cpp][C++]] | | 38 | | Bucketing or sorting | [[https://www.interviewbit.com/problems/largest-number/][Largest Number]] | [[/C++/largestNum.cpp][C++]] | | 39 | | Bucketing or sorting | Max Distance | | | 40 | | Bucketing or sorting | Maximum Consecutive Gap | | | 41 | | Bucketing or sorting | [[https://www.interviewbit.com/problems/find-duplicate-in-array/][Find Duplicate in Array]] | [[/C++/repeatedNum.cpp][C++]] | | 42 | | Value ranges | [[https://www.interviewbit.com/problems/merge-intervals/][Merge Intervals]] | [[/C++/mergeIntervals.cpp][C++]] | | 43 | | Value ranges | Merge Overlapping Intervals | | | 44 | | Space recycle | [[https://www.interviewbit.com/problems/set-matrix-zeros/][Set Matrix Zeros]] | [[/C++/setMatrixZeros.cpp][C++]] | | 45 | | Space recycle | First Missing Integer | | | 46 | | Missing / repeated number | First Missing Integer | | | 47 | | Missing / repeated number | Repeat and Missing Number Array | | | 48 | | Missing / repeated number | Find Duplicate in Array | | | 49 | | Missing / repeated number | N/3 Repeat Number | | | 50 | 51 | ** [[http://interviewbit.com/courses/programming/topics/math/][Math]] 52 | | SubTopic | Title | Solution | Notes | 53 | | | | | | 54 | |-----------------+--------------------------------------+------------+-------| 55 | | Adhoc | [[https://www.interviewbit.com/problems/prime-sum/][Prime Sum]] | [[file:Python/primeSum.py][Python]] [[file:C++/primeSum.cpp][C++]] | | 56 | | Adhoc | [[https://www.interviewbit.com/problems/power-of-two-integers/][Power of Two Integers]] | [[file:C++/isPower.cpp][C++]] [[file:Python/isPower.py][Python]] | | 57 | | Base conversion | [[https://www.interviewbit.com/problems/excel-column-number/][Excel Column Number]] | [[file:C++/titleToNumber.cpp][C++]] [[file:Python/titleToNumber.py][Python]] | | 58 | | Base conversion | [[https://www.interviewbit.com/problems/excel-column-title/][Excel Column Title]] | [[file:C++/convertToTitle.cpp][C++]] [[file:Python/convertToTitle.py][Python]] | | 59 | | Digit op | [[https://www.interviewbit.com/problems/palindrome-integer/][Palindrome Integer]] | [[file:C++/isPalindrome.cpp][C++]] [[file:Python/isPalindrome.py][Python]] | | 60 | | Digit op | [[https://www.interviewbit.com/problems/reverse-integer/][Reverse Integer]] | [[file:C++/reverse.cpp][C++]] [[file:Python/reverse.py][Python]] | | 61 | | Number theory | [[https://www.interviewbit.com/problems/greatest-common-divisor/][Greatest Common Divisor]] | [[file:C++/gcd.cpp][C++]] [[file:Python/gcd.py][Python]] | | 62 | | Number theory | [[https://www.interviewbit.com/problems/trailing-zeros-in-factorial/][Trailing Zeros in Factorial]] | [[file:C++/trailingZeros.cpp][C++]] [[file:Python/trailingZeros.py][Python]] | | 63 | | Number theory | Sorted Permutation Rank | | | 64 | | Number theory | Sorted Permutation Rank with Repeats | | | 65 | | Number encoding | [[https://www.interviewbit.com/problems/rearrange-array/][Rearrange Array]] | [[file:C++/arrange.cpp][C++]] [[file:Python/arrange.py][Python]] | | 66 | | Combinatorics | [[https://www.interviewbit.com/problems/grid-unique-paths/][Grid Unique Paths]] | [[file:C++/uniquePaths.cpp][C++]] [[file:Python/uniquePaths.py][Python]] | Note the difference in length between the Python and C++ solutions | 67 | 68 | ** [[https://www.interviewbit.com/courses/programming/topics/binary-search/][Binary Search]] 69 | 70 | | SubTopic | Title | Solution | Notes | 71 | | | | | | 72 | |------------------------+-----------------------------+----------+-------| 73 | | Simple binary search | Matrix Search | | | 74 | | Simple binary search | Search for a Range | | | 75 | | Simple binary search | Sorted Insert Position | | | 76 | | Search answer | Square Root of Integer | | | 77 | | Search answer | Painter's Partition Problem | | | 78 | | Search answer | Allocate Books | | | 79 | | Search step simulation | Implement Power Function | | | 80 | | Sort modification | Rotated Sorted Array Search | | | 81 | | Sort modification | Median of Array | | | 82 | 83 | ** [[https://www.interviewbit.com/courses/programming/topics/stacks-and-queues/][Stack and Queue]] 84 | | SubTopic | Title | Solution | Notes | 85 | | Multiple Stack | [[ https://www.interviewbit.com/problems/min-stack/][Min Stack]] | [[/C++/minStack.cpp][C++]] | IB has an annoying redefinition issue in their buffer. | 86 | | Stack math | [[https://www.interviewbit.com/problems/evaluate-expression/][Evaluate Expression]] | [[/C++/evalRPN.cpp][C++]] | | 87 | | Stack Simple | [[https://www.interviewbit.com/problems/redundant-braces/][Redundant Braces]] | [[/C++/braces.cpp][C++]] | | 88 | | CleverStack | [[https://www.interviewbit.com/problems/nearest-smaller-element/][Nearest Smaller Element]] | [[/C++/prevSmaller.cpp][C++]] | Forgot to use a solution vector the first time around. | 89 | | | | | | 90 | 91 | ** [[https://www.interviewbit.com/courses/programming/topics/linked-lists/][Linked Lists]] 92 | | Subtopic | Title | Solution | Notes | 93 | | Examples | [[https://www.interviewbit.com/problems/intersection-of-linked-lists/][Intersection of Linked List]] | [[/C++/getIntersectionNode.cpp][C++]] | | 94 | | List 2 Pointer | [[https://www.interviewbit.com/problems/palindrome-list/][Palindrome List]] | [[file:C++/listPalindrome.cpp][C++]] | | 95 | | List 2 Pointer | [[https://www.interviewbit.com/problems/merge-two-sorted-lists/][Merge Sorted List]] | [[file:C++/mergeTwoLists.cpp][C++]] | | 96 | | List 2 Pointer | [[https://www.interviewbit.com/problems/remove-duplicates-from-sorted-list/][Remove Duplicates from sorted list i]] | [[file:C++/deleteDuplicatesi.cpp][C++]] | | 97 | | List 2 Pointer | [[https://www.interviewbit.com/problems/remove-duplicates-from-sorted-list-ii/][Remove Duplicates from sorted list ii]] | [[file:C++/deleteDuplicatesii.cpp][C++]] | | 98 | | List 2 Pointer | [[https://www.interviewbit.com/problems/remove-nth-node-from-list-end/][Remove nth node from list end]] | [[file:C++/removeNthFromEnd.cpp][C++]] | | 99 | | List 2 Pointer | [[https://www.interviewbit.com/problems/rotate-list/][Rotate List]] | [[file:C++/rotateRight.cpp][C++]] | | 100 | | List 2 Pointer | [[https://www.interviewbit.com/problems/reverse-link-list-ii/][Reverse Linked List II]] | [[file:C++/reverseBetween.cpp][C++]] | | 101 | | List 2 Pointer | [[https://www.interviewbit.com/problems/reorder-list/][Reorder List]] | [[file:C++/reorderList.cpp][C++]] [[file:Python/reorderList.py][Python]] | | 102 | | List Math | [[https://www.interviewbit.com/problems/add-two-numbers-as-lists/][Add Two Numbers as Lists]] | [[file:C++/addTwoNumber.cpp][C++]] [[file:Python/addTwoNumbers.py][Python]] | | 103 | | List Math | [[https://www.interviewbit.com/problems/list-cycle/][List Cycle]] | [[file:C++/detectCycle.cpp][C++]] [[file:Python/detectCycle.py][Python]] | Python Solution is much simpler | 104 | | List Sort | [[https://www.interviewbit.com/problems/partition-list/][Partiton List]] | [[file:C++/partition.cpp][C++]] [[file:Python/partition.py][Python]] | | 105 | -------------------------------------------------------------------------------- /img/ib-logo-square.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Alex-Keyes/InterviewBit/d0a02b1170c1391d07a8962e8ae1935e2d79ebb2/img/ib-logo-square.png -------------------------------------------------------------------------------- /repeatedNumber.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | # @param A : tuple of integers 3 | # @return a list of integers 4 | def repeatedNumber(self, A): 5 | a=list(A) 6 | a.sort() 7 | r=0 8 | m=0 9 | for i in range(0,len(a)-1): 10 | if a[i]==a[i+1]: 11 | r=a[i] 12 | break 13 | s=sum(a) 14 | d=(len(a)*(len(a)+1))/2 15 | m=r+(d-s) 16 | return [r,m] 17 | -------------------------------------------------------------------------------- /timeComplexity.md: -------------------------------------------------------------------------------- 1 | # Time Complexity 2 | Since these questions are all multiple choice I'm going to write down the write answers here 3 | 4 | ## Basic Primer 5 | | Name | Answer | 6 | | --- | --- | 7 | | [LOOP_CMPL](https://www.interviewbit.com/problems/loop_cmpl) | O(N + M) time, O(1) space | 8 | | [NESTED_CMPL](https://www.interviewbit.com/problems/nested_cmpl) | O(N * N) time, O(1) space | 9 | | [NESTED_CMPL2](https://www.interviewbit.com/problems/nested_cmpl2/) | O(N*N) | 10 | | [CHOOSE4](https://www.interviewbit.com/problems/choose4/) | X will always be a better choice for large inputs 11 | 12 | ## Math 13 | | Name | Answer | 14 | | --- | --- | 15 | | [WHILE_CMPL](https://www.interviewbit.com/problems/while_cmpl/) | O(log N) 16 | | [NESTED_CMPL3](https://www.interviewbit.com/problems/nested_cmpl3/) | O(N) 17 | 18 | 19 | ## Compare Functions 20 | | Name | Answer | 21 | | --- | --- | 22 | | [CHOOSE1](https://www.interviewbit.com/problems/choose1/) | n^3 / (sqrt(n)) 23 | | [CHOOSE2](https://www.interviewbit.com/problems/choose2/) | f3, f2, f4, f1 24 | | [CHOOSE3](https://www.interviewbit.com/problems/choose3/) | c 25 | 26 | ## Function calling itself 27 | | Name | Answer | 28 | | --- | --- | 29 | |[REC_CMPL1](https://www.interviewbit.com/problems/rec_cmpl1/) | O(N) 30 | |[REC_CMPL2](https://www.interviewbit.com/problems/rec_cmpl2/) | O(2^(R + C)) 31 | 32 | # Amortized 33 | | Name | Answer | 34 | | --- | --- | 35 | | [AMORTIZED1](https://www.interviewbit.com/problems/amortized1/) | O(N) 36 | --------------------------------------------------------------------------------