├── README.md ├── 627_Swap_Salary.py ├── 595_Big_Countries.txt ├── .vscode └── settings.json ├── 27_remove_element.py ├── reverse_string.py ├── remove_duplicates_from_sorted_array.py ├── 771_jewels_and_stones.py ├── 28_Implement_strStr().py ├── .gitignore ├── Palindrome_Number.py ├── .gitattributes ├── 7_Reverse_Integer.py ├── 709_To_Lower_Case.py ├── 001_Two-Sum.py ├── 2_Median_of_two_sorted_arrays.py ├── 905_Sort_Array_By_Parity.py ├── 645_Set_Mismatch.py ├── 1662_Check_If_Two_String_Arrays_are_Equivalent.py ├── 49_Group_Anagrams ├── 876_Middle_of_the_Linked_List ├── 766_Toeplitz_Matrix ├── 412_FizzBuzz.py ├── 6_Zigzag_Conversion.py ├── 523_Continuous_Subarray_Sum.py ├── 19_Remove_Nth_Node_From_End_of_List ├── 1239 Maximum Length of a Concatenated String with Unique Characters.yml ├── 197_Rising Temperature.sql ├── 35_Search_Insert_Position ├── 24_Swap_Nodes_in_Pairs.py ├── 13_Roman-to-Integer.py └── 8_String to Integer (atoi).py /README.md: -------------------------------------------------------------------------------- 1 | # Leetcode 2 | Solutions to problems on Leetcode in Python 3 | -------------------------------------------------------------------------------- /627_Swap_Salary.py: -------------------------------------------------------------------------------- 1 | UPDATE salary SET sex = CASE WHEN sex = 'm' THEN 'f' ELSE 'm' END; -------------------------------------------------------------------------------- /595_Big_Countries.txt: -------------------------------------------------------------------------------- 1 | SELECT name,population,area FROM World WHERE area>3000000 or population>25000000; 2 | -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "python.pythonPath": "C:\\Users\\Ranajoy\\AppData\\Local\\Programs\\Python\\Python36-32\\python.exe" 3 | } -------------------------------------------------------------------------------- /27_remove_element.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def removeElement(self, nums, val): 3 | while val in nums: 4 | nums.remove(val) 5 | return len(nums) 6 | -------------------------------------------------------------------------------- /reverse_string.py: -------------------------------------------------------------------------------- 1 | """ 2 | Write a function that takes a string as input and returns the string reversed. 3 | 4 | Example: 5 | Given s = "hello", return "olleh". 6 | """ 7 | 8 | class Solution: 9 | def reverseString(self, s): 10 | return s[::-1] 11 | 12 | -------------------------------------------------------------------------------- /remove_duplicates_from_sorted_array.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def removeDuplicates(self, nums): 3 | pos = 0 4 | while pos < len(nums)-1: 5 | if nums[pos] == nums[pos+1]: 6 | del nums[pos+1] 7 | else: 8 | pos += 1 9 | return len(nums) 10 | -------------------------------------------------------------------------------- /771_jewels_and_stones.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def numJewelsInStones(self, J, S): 3 | jewel = len(J)-1 4 | stone = len(S) 5 | count = 0 6 | while jewel >= 0: 7 | for i in range(stone): 8 | if S[i] == J[jewel]: 9 | count += 1 10 | jewel -= 1 11 | return count -------------------------------------------------------------------------------- /28_Implement_strStr().py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def strStr(self, haystack, needle): 3 | length = len(needle) 4 | if length == 0: 5 | return 0 6 | pos = -1 7 | for i in range(len(haystack)-length+1): 8 | print(haystack[i:i+length]) 9 | if haystack[i:i+length] == needle: 10 | return i 11 | return pos -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Windows thumbnail cache files 2 | Thumbs.db 3 | ehthumbs.db 4 | ehthumbs_vista.db 5 | 6 | # Folder config file 7 | Desktop.ini 8 | 9 | # Recycle Bin used on file shares 10 | $RECYCLE.BIN/ 11 | 12 | # Windows Installer files 13 | *.cab 14 | *.msi 15 | *.msm 16 | *.msp 17 | 18 | # Windows shortcuts 19 | *.lnk 20 | 21 | # ========================= 22 | # Operating System Files 23 | # ========================= 24 | -------------------------------------------------------------------------------- /Palindrome_Number.py: -------------------------------------------------------------------------------- 1 | import math 2 | class Solution: 3 | def isPalindrome(self, x): 4 | if x<0: 5 | return False 6 | else: 7 | num = 0 8 | orig = x 9 | while x>0: 10 | num = num*10 + x%10 11 | x = math.floor(x/10) 12 | if num == orig: 13 | return True 14 | else: 15 | return False 16 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto detect text files and perform LF normalization 2 | * text=auto 3 | 4 | # Custom for Visual Studio 5 | *.cs diff=csharp 6 | 7 | # Standard to msysgit 8 | *.doc diff=astextplain 9 | *.DOC diff=astextplain 10 | *.docx diff=astextplain 11 | *.DOCX diff=astextplain 12 | *.dot diff=astextplain 13 | *.DOT diff=astextplain 14 | *.pdf diff=astextplain 15 | *.PDF diff=astextplain 16 | *.rtf diff=astextplain 17 | *.RTF diff=astextplain 18 | -------------------------------------------------------------------------------- /7_Reverse_Integer.py: -------------------------------------------------------------------------------- 1 | import math 2 | class Solution: 3 | def reverse(self, x): 4 | orig=x 5 | num=0 6 | x=abs(x) 7 | while x>0: 8 | try: 9 | num = num * 10 + x % 10 10 | x=math.floor(x / 10) 11 | except: 12 | break 13 | if num>math.pow(2, 31): 14 | return 0 15 | if orig<0: 16 | return(num-2*num) 17 | else: 18 | return(num) -------------------------------------------------------------------------------- /709_To_Lower_Case.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def toLowerCase(self, str): 3 | caps = {'A':'a','B':'b','C':'c','D':'d','E':'e','F':'f','G':'g','H':'h','I':'i','J':'j','K':'k','L':'l','M':'m','N':'n','O':'o','P':'p','Q':'q','R':'r','S':'s','T':'t','U':'u','V':'v','W':'w','X':'x','Y':'y','Z':'z'} 4 | string = '' 5 | for i in str: 6 | if i in caps: 7 | string+=caps[i] 8 | continue 9 | string+=i 10 | return string -------------------------------------------------------------------------------- /001_Two-Sum.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given an array of integers, return indices of the two numbers such that they add up to a specific target. 3 | 4 | You may assume that each input would have exactly one solution, and you may not use the same element twice. 5 | 6 | Example: 7 | 8 | Given nums = [2, 7, 11, 15], target = 9, 9 | 10 | Because nums[0] + nums[1] = 2 + 7 = 9, 11 | return [0, 1]. 12 | """ 13 | 14 | class Solution: 15 | def twosum(self, nums, target): 16 | mydict = {} 17 | for i, num in enumerate(nums): 18 | if (target-num) in mydict: 19 | return mydict[target-num], i 20 | mydict[num] = i 21 | 22 | -------------------------------------------------------------------------------- /2_Median_of_two_sorted_arrays.py: -------------------------------------------------------------------------------- 1 | """ 2 | There are two sorted arrays nums1 and nums2 of size m and n respectively. 3 | Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)). 4 | You may assume nums1 and nums2 cannot be both empty. 5 | 6 | Example 1: 7 | nums1 = [1, 3] 8 | nums2 = [2] 9 | The median is 2.0 10 | 11 | Example 2: 12 | nums1 = [1, 2] 13 | nums2 = [3, 4] 14 | The median is (2 + 3)/2 = 2.5 15 | """ 16 | 17 | class Solution: 18 | def findMedianSortedArrays(self, nums1, nums2): 19 | nums1 = sorted(nums1+nums2) 20 | length = len(nums1) 21 | if length%2==0: 22 | return ((nums1[length//2]+nums1[(length//2)-1])/2) 23 | else: 24 | return (nums1[(length//2)]) 25 | -------------------------------------------------------------------------------- /905_Sort_Array_By_Parity.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an array A of non-negative integers, return an array consisting of all the even elements of A, followed by all the odd elements of A. 3 | You may return any answer array that satisfies this condition. 4 | 5 | Example 1: 6 | Input: [3,1,2,4] 7 | Output: [2,4,3,1] 8 | The outputs [4,2,3,1], [2,4,1,3], and [4,2,1,3] would also be accepted. 9 | ''' 10 | 11 | class Solution: 12 | def sortArrayByParity(self, A): 13 | 14 | n = len(A) 15 | B=[0]*n 16 | start, end = 0, n-1 17 | 18 | for i in range(n): 19 | if A[i]%2==0: 20 | B[start]=A[i] 21 | start+=1 22 | else: 23 | B[end]=A[i] 24 | end-=1 25 | return B 26 | -------------------------------------------------------------------------------- /645_Set_Mismatch.py: -------------------------------------------------------------------------------- 1 | """ 2 | You have a set of integers s, which originally contains all the numbers from 1 to n. Unfortunately, due to some error, one of the numbers in s got duplicated to another number in the set, which results in repetition of one number and loss of another number. 3 | 4 | You are given an integer array nums representing the data status of this set after the error. 5 | 6 | Find the number that occurs twice and the number that is missing and return them in the form of an array. 7 | 8 | Example 1: 9 | Input: nums = [1,2,2,4] 10 | Output: [2,3] 11 | 12 | Example 2: 13 | Input: nums = [1,1] 14 | Output: [1,2] 15 | """ 16 | 17 | class Solution: 18 | def findErrorNums(self, nums: List[int]) -> List[int]: 19 | reference = range(1, len(nums) + 1) 20 | dedup = set(nums) 21 | return [sum(nums) - sum(dedup), sum(reference) - sum(dedup)] 22 | -------------------------------------------------------------------------------- /1662_Check_If_Two_String_Arrays_are_Equivalent.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given two string arrays word1 and word2, return true if the two arrays represent the same string, and false otherwise. 3 | A string is represented by an array if the array elements concatenated in order forms the string. 4 | 5 | Example 1: 6 | Input: word1 = ["ab", "c"], word2 = ["a", "bc"] 7 | Output: true 8 | Explanation: 9 | word1 represents string "ab" + "c" -> "abc" 10 | word2 represents string "a" + "bc" -> "abc" 11 | The strings are the same, so return true. 12 | 13 | Example 2: 14 | Input: word1 = ["a", "cb"], word2 = ["ab", "c"] 15 | Output: false 16 | 17 | Example 3: 18 | Input: word1 = ["abc", "d", "defg"], word2 = ["abcddefg"] 19 | Output: true 20 | """ 21 | 22 | 23 | class Solution: 24 | def arrayStringsAreEqual(self, word1: List[str], word2: List[str]) -> bool: 25 | return ''.join(word1)==''.join(word2) 26 | -------------------------------------------------------------------------------- /49_Group_Anagrams: -------------------------------------------------------------------------------- 1 | """ 2 | Given an array of strings strs, group the anagrams together. You can return the answer in any order. 3 | An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. 4 | 5 | Example 1: 6 | Input: strs = ["eat","tea","tan","ate","nat","bat"] 7 | Output: [["bat"],["nat","tan"],["ate","eat","tea"]] 8 | 9 | Example 2: 10 | Input: strs = [""] 11 | Output: [[""]] 12 | 13 | Example 3: 14 | Input: strs = ["a"] 15 | Output: [["a"]] 16 | """ 17 | 18 | class Solution: 19 | def groupAnagrams(self, strs: List[str]) -> List[List[str]]: 20 | groups = {} 21 | for word in strs: 22 | s_word = "".join(sorted(word)) 23 | if s_word in groups: 24 | groups[s_word].append(word) 25 | else: 26 | groups[s_word] = [word] 27 | return groups.values() 28 | -------------------------------------------------------------------------------- /876_Middle_of_the_Linked_List: -------------------------------------------------------------------------------- 1 | """ 2 | Given the head of a singly linked list, return the middle node of the linked list. 3 | If there are two middle nodes, return the second middle node. 4 | 5 | Example 1: 6 | Input: head = [1,2,3,4,5] 7 | Output: [3,4,5] 8 | Explanation: The middle node of the list is node 3. 9 | 10 | Example 2: 11 | Input: head = [1,2,3,4,5,6] 12 | Output: [4,5,6] 13 | Explanation: Since the list has two middle nodes with values 3 and 4, we return the second one. 14 | """ 15 | 16 | # Definition for singly-linked list.j 17 | # class ListNode: 18 | # def __init__(self, val=0, next=None): 19 | # self.val = val 20 | # self.next = next 21 | class Solution: 22 | def middleNode(self, head: Optional[ListNode]) -> Optional[ListNode]: 23 | fast = slow = head 24 | while fast and fast.next: 25 | slow = slow.next 26 | fast = fast.next.next 27 | return slow 28 | -------------------------------------------------------------------------------- /766_Toeplitz_Matrix: -------------------------------------------------------------------------------- 1 | """ 2 | Given an m x n matrix, return true if the matrix is Toeplitz. Otherwise, return false. 3 | A matrix is Toeplitz if every diagonal from top-left to bottom-right has the same elements. 4 | 5 | Example 1: 6 | Input: matrix = [[1,2,3,4],[5,1,2,3],[9,5,1,2]] 7 | Output: true 8 | Explanation: 9 | In the above grid, the diagonals are: 10 | "[9]", "[5, 5]", "[1, 1, 1]", "[2, 2, 2]", "[3, 3]", "[4]". 11 | In each diagonal all elements are the same, so the answer is True. 12 | 13 | Example 2: 14 | Input: matrix = [[1,2],[2,2]] 15 | Output: false 16 | Explanation: 17 | The diagonal "[1, 2]" has different elements. 18 | """ 19 | 20 | 21 | class Solution: 22 | def isToeplitzMatrix(self, matrix: List[List[int]]) -> bool: 23 | m = len(matrix) 24 | n = len(matrix[0]) 25 | 26 | for i in range(1, m): 27 | for j in range(1, n): 28 | if matrix[i][j]!=matrix[i-1][j-1]: 29 | return False 30 | return True 31 | -------------------------------------------------------------------------------- /412_FizzBuzz.py: -------------------------------------------------------------------------------- 1 | """ 2 | Write a program that outputs the string representation of numbers from 1 to n. 3 | But for multiples of three it should output “Fizz” instead of the number and for the multiples of five output “Buzz”. For numbers which are multiples of both three and five output “FizzBuzz”. 4 | Example: 5 | n = 15, 6 | Return: 7 | [ 8 | "1", 9 | "2", 10 | "Fizz", 11 | "4", 12 | "Buzz", 13 | "Fizz", 14 | "7", 15 | "8", 16 | "Fizz", 17 | "Buzz", 18 | "11", 19 | "Fizz", 20 | "13", 21 | "14", 22 | "FizzBuzz" 23 | ] 24 | """ 25 | 26 | class Solution: 27 | def fizzBuzz(self, n): 28 | res = [] 29 | 30 | for i in range(1,n+1): 31 | if i%3==0 and i%5==0: 32 | res.append("FizzBuzz") 33 | elif i%3 == 0: 34 | res.append("Fizz") 35 | elif i%5 == 0: 36 | res.append("Buzz") 37 | else: 38 | res.append(str(i)) 39 | return res 40 | 41 | 42 | -------------------------------------------------------------------------------- /6_Zigzag_Conversion.py: -------------------------------------------------------------------------------- 1 | ''' 2 | 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) 3 | 4 | P A H N 5 | A P L S I I G 6 | Y I R 7 | And then read line by line: "PAHNAPLSIIGYIR" 8 | 9 | Write the code that will take a string and make this conversion given a number of rows: 10 | 11 | string convert(string s, int numRows); 12 | Example 1: 13 | 14 | Input: s = "PAYPALISHIRING", numRows = 3 15 | Output: "PAHNAPLSIIGYIR" 16 | Example 2: 17 | 18 | Input: s = "PAYPALISHIRING", numRows = 4 19 | Output: "PINALSIGYAHRPI" 20 | Explanation: 21 | 22 | P I N 23 | A L S I G 24 | Y A H R 25 | P I 26 | ''' 27 | 28 | class Solution: 29 | def convert(self, s, numRows): 30 | if numRows == 1: 31 | return s 32 | rows = [""] * numRows 33 | point,row = -1, 0 34 | for i in range(len(s)): 35 | rows[row]+=s[i] 36 | if (row == 0 or row==numRows-1): 37 | point *= -1 38 | row+=point 39 | return "".join(rows) -------------------------------------------------------------------------------- /523_Continuous_Subarray_Sum.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given an integer array nums and an integer k, return true if nums has a continuous subarray of size at least two whose elements sum up to a multiple of k, or false otherwise. 3 | An integer x is a multiple of k if there exists an integer n such that x = n * k. 0 is always a multiple of k. 4 | 5 | Example 1: 6 | 7 | Input: nums = [23,2,4,6,7], k = 6 8 | Output: true 9 | Explanation: [2, 4] is a continuous subarray of size 2 whose elements sum up to 6. 10 | 11 | Example 2: 12 | Input: nums = [23,2,6,4,7], k = 6 13 | Output: true 14 | Explanation: [23, 2, 6, 4, 7] is an continuous subarray of size 5 whose elements sum up to 42. 15 | 42 is a multiple of 6 because 42 = 7 * 6 and 7 is an integer. 16 | """ 17 | 18 | class Solution: 19 | def checkSubarraySum(self, nums: List[int], k: int) -> bool: 20 | hmap = { 0:-1 } 21 | totals = 0 22 | 23 | for i, n in enumerate(nums): 24 | totals += n 25 | rem = totals % k 26 | if rem not in hmap: 27 | hmap[rem] = i 28 | elif i - hmap[rem] > 1: 29 | return True 30 | else: 31 | return False 32 | -------------------------------------------------------------------------------- /19_Remove_Nth_Node_From_End_of_List: -------------------------------------------------------------------------------- 1 | """ 2 | Given the head of a linked list, remove the nth node from the end of the list and return its head. 3 | 4 | Example 1: 5 | Input: head = [1,2,3,4,5], n = 2 6 | Output: [1,2,3,5] 7 | 8 | Example 2: 9 | Input: head = [1], n = 1 10 | Output: [] 11 | 12 | Example 3: 13 | Input: head = [1,2], n = 1 14 | Output: [1] 15 | """ 16 | 17 | # Definition for singly-linked list. 18 | # class ListNode: 19 | # def __init__(self, val=0, next=None): 20 | # self.val = val 21 | # self.next = next 22 | class Solution: 23 | def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]: 24 | # count total number of nodes in given linkedlist 25 | total_nodes = 0 26 | current = head 27 | while current: 28 | total_nodes += 1 29 | current = current.next 30 | 31 | # return empty if linkedlist contains single node and that needs to be removed 32 | if total_nodes==n: 33 | return head.next 34 | 35 | # reach the previous node before the node which needs to be removed 36 | current=head 37 | for i in range(total_nodes-n-1): 38 | current = current.next 39 | current.next = current.next.next # change the pointer to skip nth node 40 | 41 | return head 42 | -------------------------------------------------------------------------------- /1239 Maximum Length of a Concatenated String with Unique Characters.yml: -------------------------------------------------------------------------------- 1 | ''' 2 | You are given an array of strings arr. A string s is formed by the concatenation of a subsequence of arr that has unique characters. 3 | Return the maximum possible length of s. 4 | A subsequence is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements. 5 | 6 | Example 1: 7 | Input: arr = ["un","iq","ue"] 8 | Output: 4 9 | Explanation: All the valid concatenations are: 10 | - "" 11 | - "un" 12 | - "iq" 13 | - "ue" 14 | - "uniq" ("un" + "iq") 15 | - "ique" ("iq" + "ue") 16 | Maximum length is 4. 17 | 18 | Example 2: 19 | Input: arr = ["cha","r","act","ers"] 20 | Output: 6 21 | Explanation: Possible longest valid concatenations are "chaers" ("cha" + "ers") and "acters" ("act" + "ers"). 22 | ''' 23 | 24 | class Solution: 25 | def maxLength(self, arr: List[str]) -> int: 26 | subs = [""] 27 | prev_max = 0 28 | 29 | for word in arr: 30 | for sub_word in subs: 31 | new_sub = sub_word+word 32 | # skip if concatenated substitution is unique 33 | if len(new_sub)!=len(set(new_sub)): 34 | continue 35 | subs.append(new_sub) 36 | prev_max = max(prev_max, len(new_sub)) 37 | return prev_max -------------------------------------------------------------------------------- /197_Rising Temperature.sql: -------------------------------------------------------------------------------- 1 | """Table: Weather 2 | 3 | +---------------+---------+ 4 | | Column Name | Type | 5 | +---------------+---------+ 6 | | id | int | 7 | | recordDate | date | 8 | | temperature | int | 9 | +---------------+---------+ 10 | id is the primary key for this table. 11 | This table contains information about the temperature on a certain day. 12 | 13 | Write an SQL query to find all dates' Id with higher temperatures compared to its previous dates (yesterday). 14 | Return the result table in any order. 15 | 16 | The query result format is in the following example. 17 | 18 | Example 1: 19 | Input: 20 | Weather table: 21 | +----+------------+-------------+ 22 | | id | recordDate | temperature | 23 | +----+------------+-------------+ 24 | | 1 | 2015-01-01 | 10 | 25 | | 2 | 2015-01-02 | 25 | 26 | | 3 | 2015-01-03 | 20 | 27 | | 4 | 2015-01-04 | 30 | 28 | +----+------------+-------------+ 29 | Output: 30 | +----+ 31 | | id | 32 | +----+ 33 | | 2 | 34 | | 4 | 35 | +----+ 36 | Explanation: 37 | In 2015-01-02, the temperature was higher than the previous day (10 -> 25). 38 | In 2015-01-04, the temperature was higher than the previous day (20 -> 30). 39 | """ 40 | 41 | # Write your MySQL query statement below 42 | select Weather.id 43 | from Weather 44 | join Weather as w2 45 | on DATEDIFF(Weather.recordDate,w2.recordDate) = 1 46 | and Weather.temperature > w2.temperature 47 | -------------------------------------------------------------------------------- /35_Search_Insert_Position: -------------------------------------------------------------------------------- 1 | """ 2 | Given a sorted array of distinct integers 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. 3 | 4 | You must write an algorithm with O(log n) runtime complexity. 5 | 6 | Example 1: 7 | Input: nums = [1,3,5,6], target = 5 8 | Output: 2 9 | 10 | Example 2: 11 | Input: nums = [1,3,5,6], target = 2 12 | Output: 1 13 | 14 | Example 3: 15 | Input: nums = [1,3,5,6], target = 7 16 | Output: 4 17 | 18 | """ 19 | 20 | class Solution: 21 | def searchInsert(self, nums: List[int], target: int) -> int: 22 | if target>nums[-1]: # check if target is less than first element 23 | return len(nums) 24 | elif target<=nums[0]: # check if target is greater than last element 25 | return 0 26 | result = self.binarySearch(nums, target) # search for position 27 | return result 28 | 29 | def binarySearch(self, array: List[int], target, start_index = 0): 30 | mid = len(array)//2 31 | if mid==0: # if target not found in array 32 | return start_index+1 33 | elif array[mid] == target: 34 | return start_index+mid 35 | elif array[mid]target: 39 | return self.binarySearch(array[:mid], target, start_index) 40 | 41 | -------------------------------------------------------------------------------- /24_Swap_Nodes_in_Pairs.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a linked list, swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the list's nodes (i.e., only nodes themselves may be changed.) 3 | 4 | Example 1: 5 | Input: head = [1,2,3,4] 6 | Output: [2,1,4,3] 7 | 8 | Example 2: 9 | Input: head = [] 10 | Output: [] 11 | 12 | Example 3: 13 | Input: head = [1] 14 | Output: [1] 15 | 16 | Constraints: 17 | 18 | - The number of nodes in the list is in the range [0, 100]. 19 | - 0 <= Node.val <= 100 20 | """ 21 | 22 | # Definition for singly-linked list. 23 | # class ListNode: 24 | # def __init__(self, val=0, next=None): 25 | # self.val = val 26 | # self.next = next 27 | class Solution: 28 | 29 | def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]: 30 | # fake node to save the starting point 31 | fake_node = ListNode(next=head) 32 | 33 | # instantiate 34 | prev_node = fake_node 35 | current_node = head 36 | 37 | while current_node and current_node.next: 38 | # save the pointers 39 | next_node = current_node.next 40 | nextpair = current_node.next.next 41 | 42 | # swap pointers 43 | next_node.next = current_node 44 | current_node.next = nextpair 45 | prev_node.next = next_node 46 | 47 | # increment 48 | prev_node = current_node 49 | current_node = nextpair 50 | return fake_node.next 51 | -------------------------------------------------------------------------------- /13_Roman-to-Integer.py: -------------------------------------------------------------------------------- 1 | """ 2 | Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. 3 | Symbol Value 4 | I 1 5 | V 5 6 | X 10 7 | L 50 8 | C 100 9 | D 500 10 | M 1000 11 | For example, two is written as II in Roman numeral, just two one's added together. Twelve is written as, XII, which is simply X + II. The number twenty seven is written as XXVII, which is XX + V + II. 12 | 13 | Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used: 14 | 15 | I can be placed before V (5) and X (10) to make 4 and 9. 16 | X can be placed before L (50) and C (100) to make 40 and 90. 17 | C can be placed before D (500) and M (1000) to make 400 and 900. 18 | Given a roman numeral, convert it to an integer. Input is guaranteed to be within the range from 1 to 3999. 19 | 20 | Example 1: 21 | Input: "III" 22 | Output: 3 23 | 24 | Example 2: 25 | Input: "IV" 26 | Output: 4 27 | """ 28 | 29 | class Solution: 30 | def toInt(self,i): 31 | if i == 'M': 32 | return 1000 33 | elif i == 'D': 34 | return 500 35 | elif i == 'C': 36 | return 100 37 | elif i == 'L': 38 | return 50 39 | elif i == 'X': 40 | return 10 41 | elif i == 'V': 42 | return 5 43 | elif i == 'I': 44 | return 1 45 | 46 | def romanToInt(self, s): 47 | s=list(s) 48 | summ=0 49 | flag=0 50 | for i in range(len(s)): 51 | current = self.toInt(s[i]) 52 | if flag == 1: 53 | flag = 0 54 | continue 55 | if i+1 < len(s): 56 | print('current : ',current) 57 | nextt = self.toInt(s[i+1]) 58 | print('next : ',nextt) 59 | if nextt <= current: 60 | summ += current 61 | print(i,summ) 62 | else: 63 | summ = summ + nextt - current 64 | flag = 1 65 | print("***",i,summ) 66 | else: 67 | summ += current 68 | print('else',summ,current) 69 | return summ 70 | -------------------------------------------------------------------------------- /8_String to Integer (atoi).py: -------------------------------------------------------------------------------- 1 | """Implement the myAtoi(string s) function, which converts a string to a 32-bit signed integer (similar to C/C++'s atoi function). 2 | 3 | The algorithm for myAtoi(string s) is as follows: 4 | 5 | Read in and ignore any leading whitespace. 6 | Check if the next character (if not already at the end of the string) is '-' or '+'. Read this character in if it is either. This determines if the final result is negative or positive respectively. Assume the result is positive if neither is present. 7 | Read in next the characters until the next non-digit character or the end of the input is reached. The rest of the string is ignored. 8 | Convert these digits into an integer (i.e. "123" -> 123, "0032" -> 32). If no digits were read, then the integer is 0. Change the sign as necessary (from step 2). 9 | If the integer is out of the 32-bit signed integer range [-231, 231 - 1], then clamp the integer so that it remains in the range. Specifically, integers less than -231 should be clamped to -231, and integers greater than 231 - 1 should be clamped to 231 - 1. 10 | Return the integer as the final result. 11 | Note: 12 | 13 | Only the space character ' ' is considered a whitespace character. 14 | Do not ignore any characters other than the leading whitespace or the rest of the string after the digits. 15 | 16 | 17 | Example 1: 18 | 19 | Input: s = "42" 20 | Output: 42 21 | Explanation: The underlined characters are what is read in, the caret is the current reader position. 22 | Step 1: "42" (no characters read because there is no leading whitespace) 23 | ^ 24 | Step 2: "42" (no characters read because there is neither a '-' nor '+') 25 | ^ 26 | Step 3: "42" ("42" is read in) 27 | ^ 28 | The parsed integer is 42. 29 | Since 42 is in the range [-231, 231 - 1], the final result is 42. 30 | Example 2: 31 | 32 | Input: s = " -42" 33 | Output: -42 34 | Explanation: 35 | Step 1: " -42" (leading whitespace is read and ignored) 36 | ^ 37 | Step 2: " -42" ('-' is read, so the result should be negative) 38 | ^ 39 | Step 3: " -42" ("42" is read in) 40 | ^ 41 | The parsed integer is -42. 42 | Since -42 is in the range [-231, 231 - 1], the final result is -42. 43 | """ 44 | 45 | class Solution: 46 | def myAtoi(self, s: str) -> int: 47 | sign = 1 48 | num_found = False 49 | result = 0 50 | nums = [str(num) for num in range(10)] 51 | non_nums = ['+', '-'] 52 | for i in s.strip(): 53 | if i in nums: 54 | num_found = True 55 | result = result * 10 + int(i) 56 | elif (i not in nums and i not in non_nums) or (num_found and i not in nums): 57 | break 58 | elif i in non_nums: 59 | sign = 1 if i=='+' else -1 60 | num_found = True 61 | result *= sign 62 | return max(-2**31, min(result, 2**31 - 1)) 63 | --------------------------------------------------------------------------------