diff --git a/GeeksForGeeks/Amazon/Addition of submatrix.py b/GeeksForGeeks/Amazon/Addition of submatrix.py new file mode 100644 index 0000000..75af318 --- /dev/null +++ b/GeeksForGeeks/Amazon/Addition of submatrix.py @@ -0,0 +1,23 @@ +''' +Given a matrix C of size N x M. You are given position of submatrix as X1, Y1 and X2, Y2 inside the matrix. +Find the sum of all elements inside that submatrix. +''' + +if __name__ =='__main__': + t = int(input()) + for _ in range(t): + size = list(map(int,input().split())) + n , m = size[0],size[1] + l = list(map(int,input().split())) + matrix = [[l[j] for j in range(i,i+m)] for i in range(0,n*m,m)] + + s = list(map(int,input().split())) + x1 , y1 , x2, y2 = s[0]-1,s[1]-1,s[2]-1,s[3]-1 + + Sum = 0 + for i in range(x1,x2+1): + for j in range(y1,y2+1): + Sum += matrix[i][j] + + print(Sum) + diff --git a/GeeksForGeeks/Amazon/Check set bits.cpp b/GeeksForGeeks/Amazon/Check set bits.cpp new file mode 100644 index 0000000..a88c5ef --- /dev/null +++ b/GeeksForGeeks/Amazon/Check set bits.cpp @@ -0,0 +1,33 @@ +/* +Given a number N. Write a program to check whether every bit in the binary representation of the given number is set or not. +*/ + +#include +using namespace std; + +bool Check(int n) +{ + while(n > 0) + { + if(!(n & 1)) + return false; + + n = n>>1; + } + return true; +} +int main() + { + int t; + cin>>t; + while(t--) + { + int n; + cin>>n; + if(Check(n)) + cout<<"YES"<0: + s = input() + + x = s.count('1') + res = (x * (x-1))//2 + print(res) + ''' + res = 0 + for i in range(len(s)): + if s[i] == '1': + for j in range(i+1,len(s)): + if s[j] == '1': + res += 1 + print(res) + ''' + t -= 1 diff --git a/GeeksForGeeks/Amazon/Count the elements.py b/GeeksForGeeks/Amazon/Count the elements.py new file mode 100644 index 0000000..da40448 --- /dev/null +++ b/GeeksForGeeks/Amazon/Count the elements.py @@ -0,0 +1,26 @@ +''' +Given two arrays A and B. Given Q queries each having a positive integer i denoting an index of the array A. +For each query, your task is to find all the elements less than or equal to Ai in the array B. +''' + +def BinarySearch(low,high,A,ele): + while low<= high : + mid = (low + high)//2 + if A[mid] <= ele : + low = mid+1 + else: + high = mid-1; + return high + +if __name__ == '__main__': + t = int(input()) + for _ in range(t): + n = int(input()) + A = list(map(int,input().split())) + B = list(map(int,input().split())) + B.sort() + Q = int(input()) + for q in range(Q): + ind = int(input()) + searchind = BinarySearch(0,n-1,B,A[ind]) + print(searchind+1) diff --git a/GeeksForGeeks/Amazon/Delete nodes having greater value on right.cpp b/GeeksForGeeks/Amazon/Delete nodes having greater value on right.cpp new file mode 100644 index 0000000..fd2ff5b --- /dev/null +++ b/GeeksForGeeks/Amazon/Delete nodes having greater value on right.cpp @@ -0,0 +1,95 @@ +/* +Given a singly linked list, remove all the nodes which have a greater value on right side. +*/ + +#include +using namespace std; +struct Node +{ +int data; +Node* next; +}; +Node *newNode(int data) +{ + Node *new_node = new Node; + new_node->data = data; + new_node->next = NULL; + return new_node; +} +void print(Node *root) +{ +Node *temp = root; +while(temp!=NULL) +{ +cout<data<<" "; +temp=temp->next; +} +} +Node *compute(Node *head); +int main() +{ + int T; + cin>>T; + while(T--) + { + int K; + cin>>K; + struct Node *head = NULL; + struct Node *temp = head; + for(int i=0;i>data; + if(head==NULL) + head=temp=newNode(data); + else + { + temp->next = newNode(data); + temp=temp->next; + } + } + Node *result = compute(head); + print(result); + cout<next; + curr->next = prev; + prev = curr; + curr = q; + } + + Node *R = prev; + Node *p = R; + int max = p->data; + while(p->next != NULL) + { + if(p->next->data < max) + { + p->next = (p->next != NULL)? p->next->next : NULL; + } + else + { + max = p->next->data; + p = p->next; + } + } + + Node *Curr = R; + Node *Prev = NULL , *Q = NULL; + while(Curr != NULL) + { + Q = Curr->next; + Curr->next = Prev; + Prev = Curr; + Curr = Q; + } + + return Prev; +} diff --git a/GeeksForGeeks/Amazon/Largest number in K swaps.cpp b/GeeksForGeeks/Amazon/Largest number in K swaps.cpp new file mode 100644 index 0000000..0344ec1 --- /dev/null +++ b/GeeksForGeeks/Amazon/Largest number in K swaps.cpp @@ -0,0 +1,46 @@ +''' +Given a number K and string S of digits denoting a positive integer, build the largest number possible by performing swap operations on +the digits of S atmost K times. +''' + +#include +using namespace std; + +void findMaximumNum(string str, int k, string& max) +{ + if(k == 0) + return; + + int n = str.length(); + for (int i = 0; i < n - 1; i++) + { + for (int j = i + 1; j < n; j++) + { + if (str[i] < str[j]) + { + swap(str[i], str[j]); + if (str.compare(max) > 0) + max = str; + findMaximumNum(str, k - 1, max); + swap(str[i], str[j]); + } + } + } +} + +int main() +{ + int t; + cin>>t; + while(t--) + { + int k; + cin>>k; + string str; + cin>>str; + string max = str; + findMaximumNum(str, k, max); + cout<0: + n = int(input()) + A = list(map(int,input().split())) + A.sort() + print(A[n-1]) + + t -= 1 diff --git a/GeeksForGeeks/Amazon/Reverse a Linked List in groups of given size.cpp b/GeeksForGeeks/Amazon/Reverse a Linked List in groups of given size.cpp new file mode 100644 index 0000000..632a308 --- /dev/null +++ b/GeeksForGeeks/Amazon/Reverse a Linked List in groups of given size.cpp @@ -0,0 +1,85 @@ +/* +Given a linked list of size N. The task is to reverse every k nodes (where k is an input to the function) in the linked list. +*/ + +#include +using namespace std; +/* Link list node */ +struct node *reverse (struct node *head, int k); +struct node +{ + int data; + struct node* next; +}*head; +/* UTILITY FUNCTIONS */ +/* Function to push a node */ + void insert() +{ + int n,value; + cin>>n; + struct node *temp; + for(int i=0;i>value; + if(i==0) + { + head=(struct node *) malloc( sizeof(struct node) ); + head->data=value; + head->next=NULL; + temp=head; + continue; + } + else + { + temp->next= (struct node *) malloc( sizeof(struct node) ); + temp=temp->next; + temp->data=value; + temp->next=NULL; + } + } +} +/* Function to print linked list */ +void printList(struct node *node) +{ + while (node != NULL) + { + printf("%d ", node->data); + node = node->next; + } +printf(" +"); +} +/* Drier program to test above function*/ +int main(void) +{ + /* Start with the empty list */ + int t,k,value,n; + cin>>t; + while(t--) + { + insert(); + cin>>k; + head = reverse(head, k); + printList(head); + } + return(0); +} + +struct node *reverse (struct node *head, int k) +{ + struct node *prev = NULL; + struct node *curr = head; + struct node *q = NULL; + int c = 0; + while(c++ < k and curr != NULL) + { + q = curr->next; + curr->next = prev; + prev = curr; + curr = q; + } + if(q != NULL) + head->next = reverse(q,k); + + return prev; +} diff --git a/GeeksForGeeks/Amazon/Single Number.cpp b/GeeksForGeeks/Amazon/Single Number.cpp new file mode 100644 index 0000000..3155736 --- /dev/null +++ b/GeeksForGeeks/Amazon/Single Number.cpp @@ -0,0 +1,26 @@ +/* +Given an array of positive integers where every element appears even times except for one. Find that number occuring odd number of times. +*/ + +#include +using namespace std; +int main() + { + int t; + cin>>t; + while(t--) + { + int n; + cin>>n; + int A[n]; + int x = 0; + for(int i =0;i>A[i]; + x = x^A[i]; + } + + cout< len(A)/2: + return True + else: + return False +# Function to print Majority Element +def printMajority(A): + # Find the candidate for Majority + cand = findCandidate(A) + + # Print the candidate if it is Majority + if isMajority(A, cand) == True: + print(cand) + else: + print("No Majority Element") + +# Driver program to test above functions +A = [2, 2, 3, 5, 2, 2, 6] +printMajority(A) diff --git a/GeeksForGeeks/Median.py b/GeeksForGeeks/Median.py new file mode 100644 index 0000000..d9acce2 --- /dev/null +++ b/GeeksForGeeks/Median.py @@ -0,0 +1,42 @@ +''' +Given two sorted arrays A and B of n elements each,describe an algorithm to find median of the union of two arrays in O(log n) time. +''' +def getMedian(A,B,n): + if n == 0 : return -1 + if n == 1 : + return (A[0]+B[0])//2 + + if n == 2 : + return (max(A[0],B[0])+min(A[1],B[1]))//2 + + m1 = median(A,n) + m2 = median(B,n) + + if m1 == m2 : + return m1 + elif m1 > m2: + if n%2 == 0: + return getMedian(A[:(n//2)+1] , B[(n//2)-1:] ,(n//2)+1) + + else : + return getMedian(A[:(n//2)+1] , B[(n//2):] , (n//2)+1) + + else : + if n%2 == 0 : + return getMedian(A[(n//2)-1:] , B[:(n//2)+1] ,(n//2)+1) + + else : + return getMedian(A[(n//2):] , B[:(n//2)+1] , (n//2)+1) + + +def median(S , l): + if l%2 == 0 : + return (S[l//2]+S[(l//2)-1])//2 + else: + return S[l//2] + +if __name__ == '__main__': + A = [1,12,15,26,38] + B = [2,13,17,30,45] + m = getMedian(A,B,5) + print(m) diff --git a/GeeksForGeeks/Remove Spaces.py b/GeeksForGeeks/Remove Spaces.py new file mode 100644 index 0000000..c8f5a3a --- /dev/null +++ b/GeeksForGeeks/Remove Spaces.py @@ -0,0 +1,7 @@ +# Given a string, remove spaces from it + +if __name__ == '__main__': + T = int(input()) + while T>0: + print(''.join(list(input().split()))) + T-=1 diff --git a/GeeksForGeeks/Sum of numbers in string.py b/GeeksForGeeks/Sum of numbers in string.py new file mode 100644 index 0000000..b7f7247 --- /dev/null +++ b/GeeksForGeeks/Sum of numbers in string.py @@ -0,0 +1,30 @@ +''' +Given a string str containing alphanumeric characters, calculate sum of all numbers present in the string. +''' +if __name__ == '__main__': + + t = int(input()) + while t>0: + + s = input() + res = 0 + i = 0 + + while i 0 and nums[i] == nums[i-1]:continue + start = i+1 + end = len(nums) - 1 + while start < end: + s = nums[i] + nums[start] + nums[end] + ans = abs(target - s) + if res == [] or ans < res[0]: + res = [ans,s] + if s == target:return s + elif s < target : start += 1 + else : end -= 1 + + return res[1] + diff --git a/LeetCode/3Sum.py b/LeetCode/3Sum.py new file mode 100644 index 0000000..73e3e7e --- /dev/null +++ b/LeetCode/3Sum.py @@ -0,0 +1,70 @@ +''' +Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero. + +Note: + +The solution set must not contain duplicate triplets. +''' +#TLE +''' +class Solution(object): + def threeSum(self, nums): + """ + :type nums: List[int] + :rtype: List[List[int]] + """ + if len(nums) < 3 : return [] + if len(nums) == 3 : return [] if sum(nums) else [nums] + nums.sort() + res = [] + for i in range(len(nums)-2): + + if nums[i] > 0 : break + start = i + 1 + end = len(nums) - 1 + + if nums[i] + nums[start] + nums[start + 1] > 0 : break + + while start < end : + l = [nums[i] , nums[start] , nums[end]] + n = sum(l) + if not n : + if l not in res : + res.append(l) + start += 1 + end -= 1 + elif n > 0 : end -= 1 + else : start += 1 + + return res +''' +class Solution(object): + def threeSum(self, nums): + """ + :type nums: List[int] + :rtype: List[List[int]] + """ + if len(nums) < 3 : return [] + if len(nums) == 3 : return [] if sum(nums) else [nums] + nums.sort() + res = [] + for i in range(len(nums)-1): + #if i is searched again,skip it + if i > 0 and nums[i] == nums[i-1]:continue + + if nums[i] > 0 : break + s = set() + j = i+1 + while j < len(nums): + rem = -(nums[i] + nums[j]) + if rem in s : + res.append([nums[i],rem,nums[j]]) + #to remove duplicates + while j < len(nums) - 1 and nums[j] == nums[j + 1]: + j = j + 1 + else: + s.add(nums[j]) + j += 1 + + return res + diff --git a/LeetCode/4Sum.py b/LeetCode/4Sum.py new file mode 100644 index 0000000..e558df0 --- /dev/null +++ b/LeetCode/4Sum.py @@ -0,0 +1,36 @@ +''' +Given an array nums of n integers and an integer target, are there elements a, b, c, and d in nums such that a + b + c + d = target? Find +all unique quadruplets in the array which gives the sum of target. +Note: +The solution set must not contain duplicate quadruplets. +''' +class Solution(object): + def fourSum(self, nums, target): + """ + :type nums: List[int] + :type target: int + :rtype: List[List[int]] + """ + + res = [] + if len(nums) < 4 : return res + if len(nums) == 4 : return [nums] if sum(nums) == target else [] + nums.sort() + for i in range(len(nums)): + if i > 0 and nums[i] == nums[i-1]:continue + for j in range(i+1,len(nums)-2): + start = j+1 + end = len(nums)-1 + while start < end: + temp = [nums[i],nums[j],nums[start],nums[end]] + t = sum(temp) + if t == target: + if temp not in res: + res.append(temp) + start += 1 + end -= 1 + elif t < target: + start += 1 + else: + end -= 1 + return res diff --git a/LeetCode/Add Two Numbers.py b/LeetCode/Add Two Numbers.py new file mode 100644 index 0000000..2f58f55 --- /dev/null +++ b/LeetCode/Add Two Numbers.py @@ -0,0 +1,44 @@ +''' +You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their +nodes contain a single digit. Add the two numbers and return it as a linked list. +You may assume the two numbers do not contain any leading zero, except the number 0 itself. +''' + +# Definition for singly-linked list. +# class ListNode(object): +# def __init__(self, x): +# self.val = x +# self.next = None + +class Solution(object): + def addTwoNumbers(self, l1, l2): + """ + :type l1: ListNode + :type l2: ListNode + :rtype: ListNode + """ + if not l1 and not l2 : return None + if not l1 : return l2 + if not l2 : return l1 + num1 = '' + while l1: + num1 += str(l1.val) + l1 = l1.next + num2 = '' + while l2: + num2 += str(l2.val) + l2 = l2.next + + num = int(num1[::-1]) + int(num2[::-1]) + num = str(num)[::-1] + + HEAD = ListNode(int(num[0])) + node = HEAD + + for i in range(1,len(num)): + node.next = ListNode(int(num[i])) + node = node.next + + return HEAD + + diff --git a/LeetCode/Array/Combination Sum.py b/LeetCode/Array/Combination Sum.py new file mode 100644 index 0000000..7ba3980 --- /dev/null +++ b/LeetCode/Array/Combination Sum.py @@ -0,0 +1,35 @@ +''' +Given a set of candidate numbers (candidates) (without duplicates) and a target number (target), find all unique combinations in candidates where the candidate numbers sums to target. + +The same repeated number may be chosen from candidates unlimited number of times. + +Note: + +All numbers (including target) will be positive integers. +The solution set must not contain duplicate combinations. +''' + +class Solution(object): + def Temporary(self,res,cur_res,candidates,remaining): + if remaining == 0 : + res.append(cur_res[:]) + return + for cand in candidates: + if cand <= remaining and (not cur_res or cur_res[-1] >= cand): + cur_res.append(cand) + self.Temporary(res,cur_res,candidates,remaining-cand) + cur_res.pop() + return + + def combinationSum(self, candidates, target): + """ + :type candidates: List[int] + :type target: int + :rtype: List[List[int]] + """ + candidates.sort(reverse = True) + res = [] + cur_res = [] + self.Temporary(res,cur_res,candidates,target) + return res + diff --git a/LeetCode/Array/Find First and Last Position of Element in Sorted Array.py b/LeetCode/Array/Find First and Last Position of Element in Sorted Array.py new file mode 100644 index 0000000..36c605e --- /dev/null +++ b/LeetCode/Array/Find First and Last Position of Element in Sorted Array.py @@ -0,0 +1,55 @@ +''' +Given an array of integers nums sorted in ascending order, find the starting and ending position of a given target value. + +Your algorithm's runtime complexity must be in the order of O(log n). + +If the target is not found in the array, return [-1, -1]. +''' +''' +# Using another approach: +def First(A,l,h,key): + while l<=h : + m = (l+h)//2 + if A[m] == key and (m == 0 or A[m-1] < key):return m + elif A[m] < key : l = m + 1 + else : h = m - 1 + return -1 + +def Last (A, l , h , key): + while l<=h : + m = (l+h)//2 + if A[m] == key and (m == len(A)-1 or A[m+1] > key):return m + elif A[m] <= key : l = m + 1 + else : h = m - 1 + return -1 + +''' +class Solution(object): + def searchRange(self, nums, target): + """ + :type nums: List[int] + :type target: int + :rtype: List[int] + """ + if not nums: return [-1,-1] + if len(nums) == 1: + if nums[0] == target: return [0,0] + return [-1,-1] + + l , h = 0, len(nums)-1 + + while l<=h: + m = (l+h)//2 + if nums[m] == target : + start , end = m , m + while start >= 1 and nums[start] == nums[start-1]: + start -= 1 + while end < len(nums)-1 and nums[end] == nums[end+1]: + end += 1 + + return [start,end] + + elif nums[m] < target : + l = m+1 + else: h = m-1 + return [-1,-1] diff --git a/LeetCode/Array/Median of Two Sorted Arrays.py b/LeetCode/Array/Median of Two Sorted Arrays.py new file mode 100644 index 0000000..2363344 --- /dev/null +++ b/LeetCode/Array/Median of Two Sorted Arrays.py @@ -0,0 +1,55 @@ +''' +There are two sorted arrays nums1 and nums2 of size m and n respectively. + +Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)). + +You may assume nums1 and nums2 cannot be both empty. +''' + +class Solution(object): + def determineMedian(self,k,A,size): + if size % 2 == 0 : + return (A[k-1]+ A[k-2]) / float(2) + else: + return A[k-1] + + def findMedianSortedArrays(self, nums1, nums2): + """ + :type nums1: List[int] + :type nums2: List[int] + :rtype: float + """ + + m , n = len(nums1),len(nums2) + + num = [0]*(m+n) + i ,j,k = 0 ,0,0 + + while i nums[i-1]: + first = i-1 + break + if first == -1: + nums[:] = sorted(nums[:]) + else: + for j in range(len(nums)-1,0,-1): + if nums[j] > nums[first]: + second = j + break + temp = nums[first] + nums[first] = nums[second] + nums[second] = temp + nums[first+1 :] = sorted(nums[first+1:]) + + diff --git a/LeetCode/Array/Search Insert Position.py b/LeetCode/Array/Search Insert Position.py new file mode 100644 index 0000000..7e96c84 --- /dev/null +++ b/LeetCode/Array/Search Insert Position.py @@ -0,0 +1,26 @@ +''' +Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were +inserted in order. + +You may assume no duplicates in the array. + +''' +class Solution(object): + def searchInsert(self, nums, target): + """ + :type nums: List[int] + :type target: int + :rtype: int + """ + l , h = 0 , len(nums)-1 + while l<=h: + m = (l+h)//2 + if nums[m] == target: return m + elif nums[m] < target : l = m+1 + else : h = m-1 + if l < len(nums) : + if nums[l] > target: return l + else: return l+1 + else: + return l + diff --git a/LeetCode/Array/Search in Rotated Sorted Array.py b/LeetCode/Array/Search in Rotated Sorted Array.py new file mode 100644 index 0000000..d4f4fd9 --- /dev/null +++ b/LeetCode/Array/Search in Rotated Sorted Array.py @@ -0,0 +1,40 @@ +''' +Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. + +(i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]). + +You are given a target value to search. If found in the array return its index, otherwise return -1. + +You may assume no duplicate exists in the array. + +Your algorithm's runtime complexity must be in the order of O(log n). +''' + +class Solution(object): + def search(self, nums, target): + """ + :type nums: List[int] + :type target: int + :rtype: int + """ + if nums == []: return -1 + + low ,high = 0 , len(nums)-1 + while low<=high : + mid = (low+high)//2 + if nums[mid] == target: + return mid + + if nums[low] <= nums[mid]: + if nums[low]<= target and nums[mid] > target: + high = mid-1 + else: + low = mid + 1 + else: + if nums[mid] < target and nums[high] >= target: + low = mid + 1 + else : + high = mid - 1 + return -1 + + diff --git a/LeetCode/Container With Most Water.py b/LeetCode/Container With Most Water.py new file mode 100644 index 0000000..e453666 --- /dev/null +++ b/LeetCode/Container With Most Water.py @@ -0,0 +1,25 @@ +''' +Given n non-negative integers a1, a2, ..., an , where each represents a point at coordinate (i, ai). n vertical lines are drawn such that +the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container +contains the most water. + +Note: You may not slant the container and n is at least 2. +''' +class Solution(object): + def maxArea(self, height): + """ + :type height: List[int] + :rtype: int + """ + first = 0 + last = len(height) - 1 + area = 0 + while first < last : + A = min(height[first],height[last]) * (last - first) + if area < A : + area = A + if height[first] < height[last]: + first += 1 + else: + last -= 1 + return area diff --git a/LeetCode/Integer to Roman.py b/LeetCode/Integer to Roman.py new file mode 100644 index 0000000..eec10e5 --- /dev/null +++ b/LeetCode/Integer to Roman.py @@ -0,0 +1,18 @@ +class Solution(object): + def intToRoman(self, num): + """ + :type num: int + :rtype: str + """ + roman = '' + number = [1,4,5,9,10,40,50,90,100,400,500,900,1000] + sym = ['I','IV','V','IX','X','XL','L','XC','C','CD','D','CM','M'] + i = 12 + while num > 0: + rem = num // number[i] + num = num % number[i] + for j in range(rem): + roman += sym[i] + + i -= 1 + return roman diff --git a/LeetCode/Letter Combinations of a Phone Number.py b/LeetCode/Letter Combinations of a Phone Number.py new file mode 100644 index 0000000..c94919b --- /dev/null +++ b/LeetCode/Letter Combinations of a Phone Number.py @@ -0,0 +1,25 @@ +''' +Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent. + +A mapping of digit to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters. +''' +phone = {'2': 'abc','3': 'def','4': 'ghi','5': 'jkl','6': 'mno','7': 'pqrs','8': 'tuv','9': 'wxyz'} +def PhoneCombination(digits,s,temp): + if digits == []: + temp.append(s) + return + for ch in phone[digits[0]]: + PhoneCombination(digits[1:],s+ch,temp) + + return temp +class Solution(object): + def letterCombinations(self, digits): + """ + :type digits: str + :rtype: List[str] + """ + s = '' + l = [] + digits = list(digits) + return PhoneCombination(digits,s,l) + diff --git a/LeetCode/Longest Common Prefix.py b/LeetCode/Longest Common Prefix.py new file mode 100644 index 0000000..a4daf5b --- /dev/null +++ b/LeetCode/Longest Common Prefix.py @@ -0,0 +1,28 @@ +''' +Write a function to find the longest common prefix string amongst an array of strings. + +If there is no common prefix, return an empty string "". +''' + +class Solution(object): + def longestCommonPrefix(self, strs): + """ + :type strs: List[str] + :rtype: str + """ + prefix = '' + if not strs: return prefix + strs.sort(key = len) + tmp = strs[0] + + for i in range(len(tmp)): + l = [] + for j in range(1,len(strs)): + if tmp[i] == strs[j][i]: + l.append(True) + else:l.append(False) + if all(l): + prefix += tmp[i] + else:break + + return prefix diff --git a/LeetCode/Longest Palindromic Substring.py b/LeetCode/Longest Palindromic Substring.py new file mode 100644 index 0000000..362f455 --- /dev/null +++ b/LeetCode/Longest Palindromic Substring.py @@ -0,0 +1,55 @@ +''' +Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000. +''' + +''' +class Solution(object): + def longestPalindrome(self, s): + """ + :type s: str + :rtype: str + """ + if not s or len(s) <= 1 : return s + size = len(s) + while size > 0 : + for i in range(len(s)-(size - 1)): + res = s[i : size+i] + if res == res[::-1]: + return res + size -= 1 + return '' +''' +def longestPalindrome(self, s): + """ + :type s: str + :rtype: str + """ + n = len(s) + maxlen = 1 + low , high = 0 , 0 + start = 0 + for i in range(1,n): + #even length + low = i-1 + high = i + while low >=0 and high maxlen: + start = low + maxlen = high-low+1 + low -= 1 + high += 1 + #odd length + low = i-1 + high = i+1 + while low >=0 and high maxlen: + start = low + maxlen = high-low+1 + low -= 1 + high += 1 + return s[start:start+maxlen] + + + + + diff --git a/LeetCode/Longest Substring Without Repeating Characters.py b/LeetCode/Longest Substring Without Repeating Characters.py new file mode 100644 index 0000000..27d1178 --- /dev/null +++ b/LeetCode/Longest Substring Without Repeating Characters.py @@ -0,0 +1,25 @@ +''' +Given a string, find the length of the longest substring without repeating characters. +''' + +class Solution(object): + def lengthOfLongestSubstring(self, s): + """ + :type s: str + :rtype: int + """ + MAX = 0 + for i in range(len(s)): + S = set() + j = i + while j < len(s): + if s[j] not in S: + S.add(s[j]) + MAX = max(len(S),MAX) + j+=1 + if j == len(s): return MAX + else: + MAX = max(len(S),MAX) + break + + return MAX diff --git a/LeetCode/Median of Two Sorted Arrays.py b/LeetCode/Median of Two Sorted Arrays.py new file mode 100644 index 0000000..ee8a9a3 --- /dev/null +++ b/LeetCode/Median of Two Sorted Arrays.py @@ -0,0 +1,25 @@ +''' +There are two sorted arrays nums1 and nums2 of size m and n respectively. + +Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)). + +You may assume nums1 and nums2 cannot be both empty. +''' + +class Solution(object): + def findMedianSortedArrays(self, nums1, nums2): + """ + :type nums1: List[int] + :type nums2: List[int] + :rtype: float + """ + nums1.extend(nums2) + nums1.sort() + n = len(nums1) + if n % 2 == 0: + first = nums1[n//2] + second = nums1[n//2 - 1] + res = (first+second)/2.0 + return res + else : + return nums1[int(n/2)] diff --git a/LeetCode/Merge Two Sorted Lists.py b/LeetCode/Merge Two Sorted Lists.py new file mode 100644 index 0000000..6db23f2 --- /dev/null +++ b/LeetCode/Merge Two Sorted Lists.py @@ -0,0 +1,35 @@ +''' +Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first +two lists. +''' +# Definition for singly-linked list. +# class ListNode(object): +# def __init__(self, x): +# self.val = x +# self.next = None + +class Solution(object): + def mergeTwoLists(self, l1, l2): + """ + :type l1: ListNode + :type l2: ListNode + :rtype: ListNode + """ + l3 = ListNode(None) + counter1 , counter2 = l1,l2 + head = l3 + while counter1 and counter2: + if counter1.val < counter2.val: + l3.next = counter1 + counter1 = counter1.next + else: + l3.next = counter2 + counter2 = counter2.next + l3 = l3.next + if counter1: + l3.next = counter1 + else: + l3.next = counter2 + + return head.next + diff --git a/LeetCode/Palindrome Number.py b/LeetCode/Palindrome Number.py new file mode 100644 index 0000000..8fb6869 --- /dev/null +++ b/LeetCode/Palindrome Number.py @@ -0,0 +1,13 @@ +''' +Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward. +''' +class Solution(object): + def isPalindrome(self, x): + """ + :type x: int + :rtype: bool + """ + x = str(x) + if x == x[::-1]:return True + return False + diff --git a/LeetCode/Regular Expression Matching.py b/LeetCode/Regular Expression Matching.py new file mode 100644 index 0000000..f154169 --- /dev/null +++ b/LeetCode/Regular Expression Matching.py @@ -0,0 +1,26 @@ +''' +Given an input string (s) and a pattern (p), implement regular expression matching with support for '.' and '*'. + +'.' Matches any single character. +'*' Matches zero or more of the preceding element. +The matching should cover the entire input string (not partial). + +Note: + +s could be empty and contains only lowercase letters a-z. +p could be empty and contains only lowercase letters a-z, and characters like . or *. +''' +import re +class Solution(object): + def isMatch(self, s, p): + """ + :type s: str + :type p: str + :rtype: bool + """ + patt = re.compile(p) + mo = re.match(p,s) + if mo and mo.start() == 0 and mo.end() == len(s): + #print(mo.span()) + return True + return False diff --git a/LeetCode/Reverse Integer.py b/LeetCode/Reverse Integer.py new file mode 100644 index 0000000..193ff01 --- /dev/null +++ b/LeetCode/Reverse Integer.py @@ -0,0 +1,47 @@ +''' +Given a 32-bit signed integer, reverse digits of an integer. +Note: +Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the +purpose of this problem,assume that your function returns 0 when the reversed integer overflows. +''' +''' +In C++: + +class Solution { +public: + int reverse(int x) + { + long long int ans = 0; + while(x!=0) + { + ans = (ans*10) + (x %10); + x = x/10; + if(ans > INT_MAX) + return 0; + if(ans < INT_MIN) + return 0; + } + return ans; + } +}; +''' +class Solution(object): + def reverse(self, x): + """ + :type x: int + :rtype: int + """ + if x == 0:return x + x = str(x) + res = '' + if x[0] == '-': + res += ''.join(x[:0:-1]) + res = res.lstrip('0') + res = '-'+res + else: + res += ''.join(x[::-1]) + res = res.lstrip('0') + + if int(res) < -pow(2,31) or int(res) > pow(2,31)-1 : return 0 + return int(res) + diff --git a/LeetCode/Roman To Integer.py b/LeetCode/Roman To Integer.py new file mode 100644 index 0000000..2c79853 --- /dev/null +++ b/LeetCode/Roman To Integer.py @@ -0,0 +1,21 @@ +class Solution(object): + def romanToInt(self, s): + """ + :type s: str + :rtype: int + """ + num = 0 + + sym = {'I': 1,'IV' : 4,'V' : 5,'IX' : 9,'X' : 10,'XL' : 40,'L' : 50,'XC' : 90,'C' : 100,'CD' : 400,'D' : 500,'CM' : 900,'M' : 1000} + + for i in range(len(s)): + if i != len(s)-1: + if sym[s[i]] >= sym[s[i+1]]: + num += sym[s[i]] + else: + num -= sym[s[i]] + else: + num += sym[s[i]] + + return num + diff --git a/LeetCode/String to Integer (atoi).py b/LeetCode/String to Integer (atoi).py new file mode 100644 index 0000000..1113d82 --- /dev/null +++ b/LeetCode/String to Integer (atoi).py @@ -0,0 +1,46 @@ +''' +mplement atoi which converts a string to an integer. + +The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting +from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as +a numerical value. +The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior +of this function. +If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str +is empty or it contains only whitespace characters, no conversion is performed. + +If no valid conversion could be performed, a zero value is returned. + +Note: + +Only the space character ' ' is considered as whitespace character. +Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. If the +numerical value is out of the range of representable values, INT_MAX (231 − 1) or INT_MIN (−231) is returned. +''' + +class Solution(object): + def myAtoi(self, string): + """ + :type str: str + :rtype: int + """ + if len(string) == 1 and not string.isdigit():return 0 + string = string.lstrip() + if string == '' or (not(string[0].isdigit()) and string[0] not in ['+','-']) : return 0 + res = '' + for ch in string: + if ch.isdigit() or (res == '' and ch in ['+','-']): + res += ch + else: + break + + if len(res) == 1 and not res.isdigit():return 0 + + if res[0] in ['+','-']: + if res[0] == '+': res = res[1:] + + if int(res) > pow(2,31) - 1 : return pow(2,31) - 1 + elif int(res) < -pow(2,31) : return -pow(2,31) + + + return int(res) diff --git a/LeetCode/Two Sum.py b/LeetCode/Two Sum.py new file mode 100644 index 0000000..230ad98 --- /dev/null +++ b/LeetCode/Two Sum.py @@ -0,0 +1,19 @@ +''' +Given an array of integers, return indices of the two numbers such that they add up to a specific target. + +You may assume that each input would have exactly one solution, and you may not use the same element twice. +''' +class Solution(object): + def twoSum(self, nums, target): + """ + :type nums: List[int] + :type target: int + :rtype: List[int] + """ + for i in range(len(nums)): + rem = target - nums[i] + if rem in nums[i+1:]: + ind = nums[i+1:].index(rem) + l = [i,i+ind+1] + return l + diff --git a/LeetCode/Valid Parentheses.py b/LeetCode/Valid Parentheses.py new file mode 100644 index 0000000..ca3cded --- /dev/null +++ b/LeetCode/Valid Parentheses.py @@ -0,0 +1,29 @@ +''' +Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. + +An input string is valid if: + +Open brackets must be closed by the same type of brackets. +Open brackets must be closed in the correct order. +Note that an empty string is also considered valid. +''' + +class Solution(object): + def isValid(self, s): + """ + :type s: str + :rtype: bool + """ + d = {'(' : 1 ,')' : 1,'{' : 3,'}': 3,'[' : 2 , ']': 2} + if s == '':return True + if len(s) % 2 != 0 : return False + stack = [] + for i in range(len(s)): + if s[i] == '(' or s[i] == '[' or s[i] == '{': + stack.append(s[i]) + elif s[i] == ')' or s[i] == ']' or s[i] == '}': + if stack == [] or d[s[i]] != d[stack[-1]]: return False + else: + stack.pop() + if stack == [] : return True + else : return False diff --git a/LeetCode/ZigZag Conversion.py b/LeetCode/ZigZag Conversion.py new file mode 100644 index 0000000..ce14380 --- /dev/null +++ b/LeetCode/ZigZag Conversion.py @@ -0,0 +1,36 @@ +''' +The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a +fixed font for better legibility) +P A H N +A P L S I I G +Y I R +And then read line by line: "PAHNAPLSIIGYIR" +Write the code that will take a string and make this conversion given a number of rows: +string convert(string s, int numRows); +''' +class Solution(object): + def convert(self, s, numRows): + """ + :type s: str + :type numRows: int + :rtype: str + """ + if numRows == 1 : + return s + + length = len(s) + l = ['' for _ in range(length)] + row = 0 + down = True + + for i in range(length): + l[row] += s[i] + if row == 0: down = True + elif row == numRows-1: down = False + + if down : row += 1 #for moving down + else: row -= 1 #for moving up + + return ''.join(l) + + diff --git a/README.md b/README.md index fac7f6a..814b771 100644 --- a/README.md +++ b/README.md @@ -62,7 +62,7 @@ c-b-a-b-c ``` * Kevin and Stuart want to play the 'The Minion Game'. ``` -Game Rules +Game Rules =: Both players are given the same string,S . Both players have to make substrings using the letters of the string S.