Skip to content

Commit 19f4532

Browse files
Solutions to leet code problems
1 parent ef4efd6 commit 19f4532

7 files changed

+372
-0
lines changed

13_Roman_to_Integer.py

+69
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
"""
2+
13. Roman to Integer
3+
Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.
4+
5+
Symbol Value
6+
I 1
7+
V 5
8+
X 10
9+
L 50
10+
C 100
11+
D 500
12+
M 1000
13+
14+
For example, 2 is written as II in Roman numeral, just two ones added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II.
15+
16+
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:
17+
18+
I can be placed before V (5) and X (10) to make 4 and 9.
19+
X can be placed before L (50) and C (100) to make 40 and 90.
20+
C can be placed before D (500) and M (1000) to make 400 and 900.
21+
22+
Given a roman numeral, convert it to an integer.
23+
24+
25+
26+
Example 1:
27+
28+
Input: s = "III"
29+
Output: 3
30+
Explanation: III = 3.
31+
32+
Example 2:
33+
34+
Input: s = "LVIII"
35+
Output: 58
36+
Explanation: L = 50, V= 5, III = 3.
37+
38+
Example 3:
39+
40+
Input: s = "MCMXCIV"
41+
Output: 1994
42+
Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.
43+
44+
"""
45+
class Solution(object):
46+
def romanToInt(self, s):
47+
"""
48+
:type s: str
49+
:rtype: int
50+
"""
51+
52+
dict1 = {"I":1, "V": 5, "X":10, "L":50, "C":100, "D":500, "M":1000 }
53+
if s[-1] not in dict1:
54+
return "invalid"
55+
result = dict1[s[-1]]
56+
57+
58+
for i in range(0,len(s)-1):
59+
if s[i] not in dict1:
60+
return "invalid "
61+
elif (dict1[s[i]]< dict1[s[i+1]]):
62+
result -= dict1[s[i]]
63+
else:
64+
result += dict1[s[i]]
65+
66+
67+
return result
68+
69+

14_Longest_Common_Prefix.py

+52
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
"""
2+
14. Longest Common Prefix
3+
Write a function to find the longest common prefix string amongst an array of strings.
4+
5+
If there is no common prefix, return an empty string "".
6+
7+
8+
9+
Example 1:
10+
11+
Input: strs = ["flower","flow","flight"]
12+
Output: "fl"
13+
14+
Example 2:
15+
16+
Input: strs = ["dog","racecar","car"]
17+
Output: ""
18+
Explanation: There is no common prefix among the input strings.
19+
20+
"""
21+
22+
class Solution(object):
23+
def longestCommonPrefix(self,strs):
24+
"""
25+
:type strs: List[str]
26+
:rtype: str
27+
"""
28+
result = ""
29+
if len(strs)<=1:
30+
return strs[0]
31+
if 1<len(strs)<=200:
32+
small_len = len(strs[0])
33+
34+
small_len = len(strs[0])
35+
36+
for idx in range(1,len(strs)):
37+
if len(strs[idx])< small_len:
38+
small_len = len(strs[idx])
39+
chr = 0
40+
while (chr<small_len):
41+
counter = 0
42+
for i in range(0,len(strs)-1):
43+
if strs[i][chr]== strs[i+1][chr]:
44+
counter +=1
45+
46+
if counter == len(strs)-1:
47+
result += strs[i][chr]
48+
else:
49+
break
50+
chr +=1
51+
52+
return result

1_Two_Sum.py

+41
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
"""1.Two Sum:
2+
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to 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+
You can return the answer in any order.
7+
8+
Example 1:
9+
10+
Input: nums = [2,7,11,15], target = 9
11+
Output: [0,1]
12+
Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].
13+
14+
Example 2:
15+
16+
Input: nums = [3,2,4], target = 6
17+
Output: [1,2]
18+
19+
Example 3:
20+
21+
Input: nums = [3,3], target = 6
22+
Output: [0,1]
23+
"""
24+
25+
26+
class Solution(object):
27+
def twoSum(self, nums, target):
28+
"""
29+
:type nums: List[int]
30+
:type target: int
31+
:rtype: List[int]
32+
"""
33+
strt = 0
34+
while strt < len(nums) - 1:
35+
for idx in range(strt+1,len(nums)):
36+
if nums[strt]+nums[idx] == target:
37+
return [strt,idx]
38+
strt +=1
39+
40+
41+

20_Valid_Parentheses.py

+47
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
2+
"""
3+
20. Valid Parentheses
4+
Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
5+
6+
An input string is valid if:
7+
8+
Open brackets must be closed by the same type of brackets.
9+
Open brackets must be closed in the correct order.
10+
Every close bracket has a corresponding open bracket of the same type.
11+
12+
13+
14+
Example 1:
15+
16+
Input: s = "()"
17+
Output: true
18+
19+
Example 2:
20+
21+
Input: s = "()[]{}"
22+
Output: true
23+
24+
Example 3:
25+
26+
Input: s = "(]"
27+
Output: false
28+
29+
"""
30+
31+
class Solution(object):
32+
def isValid(self, s):
33+
"""
34+
:type s: str
35+
:rtype: bool
36+
"""
37+
stack = []
38+
dict = {"]":"[", "}":"{", ")":"("}
39+
for char in s:
40+
if char in dict.values():
41+
stack.append(char)
42+
elif char in dict.keys():
43+
if stack == [] or dict[char] != stack.pop():
44+
return False
45+
else:
46+
return False
47+
return stack == []

268_Missing_Number.py

+29
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
"""Given an array nums containing n distinct numbers in the range [0, n], return the only number in the range that is missing from the array.
2+
e.g.1- Input: nums = [3,0,1]
3+
Output: 2
4+
Explanation: n = 3 since there are 3 numbers, so all numbers are in the range [0,3]. 2 is the missing number in the range since it does not appear in nums.
5+
e.g.2-Input: nums = [0,1]
6+
Output: 2
7+
Explanation: n = 2 since there are 2 numbers, so all numbers are in the range [0,2]. 2 is the missing number in the range since it does not appear in nums."""
8+
9+
10+
class Solution(object):
11+
def missingNumber(self, nums):
12+
"""
13+
:type nums: List[int]
14+
:rtype: int
15+
"""
16+
nums.sort()
17+
18+
# Ensure that n is at the last index
19+
if nums[-1] != len(nums):
20+
return len(nums)
21+
# Ensure that 0 is at the first index
22+
elif nums[0] != 0:
23+
return 0
24+
25+
# If we get here, then the missing number is on the range (0, n)
26+
for i in range(1, len(nums)):
27+
expected_num = nums[i-1] + 1
28+
if nums[i] != expected_num:
29+
return expected_num
+87
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
2+
"""
3+
26. Remove Duplicates from Sorted Array
4+
Given an integer array nums sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once. The relative order of the elements should be kept the same.
5+
6+
Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums. More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements.
7+
8+
Return k after placing the final result in the first k slots of nums.
9+
10+
Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory.
11+
12+
Custom Judge:
13+
14+
The judge will test your solution with the following code:
15+
16+
int[] nums = [...]; // Input array
17+
int[] expectedNums = [...]; // The expected answer with correct length
18+
19+
int k = removeDuplicates(nums); // Calls your implementation
20+
21+
assert k == expectedNums.length;
22+
for (int i = 0; i < k; i++) {
23+
assert nums[i] == expectedNums[i];
24+
}
25+
26+
If all assertions pass, then your solution will be accepted.
27+
28+
29+
30+
Example 1:
31+
32+
Input: nums = [1,1,2]
33+
Output: 2, nums = [1,2,_]
34+
Explanation: Your function should return k = 2, with the first two elements of nums being 1 and 2 respectively.
35+
It does not matter what you leave beyond the returned k (hence they are underscores).
36+
37+
Example 2:
38+
39+
Input: nums = [0,0,1,1,1,2,2,3,3,4]
40+
Output: 5, nums = [0,1,2,3,4,_,_,_,_,_]
41+
Explanation: Your function should return k = 5, with the first five elements of nums being 0, 1, 2, 3, and 4 respectively.
42+
It does not matter what you leave beyond the returned k (hence they are underscores).
43+
44+
"""
45+
46+
class Solution(object):
47+
def removeDuplicates(self, nums):
48+
"""
49+
:type nums: List[int]
50+
:rtype: int
51+
"""
52+
# idx = 1
53+
# curr = nums[0]
54+
# ptr = 1
55+
56+
# while idx< len(nums):
57+
# if nums[idx]!= curr:
58+
# if nums[ptr]>curr:
59+
# ptr +=1
60+
# idx +=1
61+
# curr = nums[ptr]
62+
63+
# else:
64+
65+
# nums[ptr]=nums[idx]
66+
# nums[idx]= curr
67+
# curr = nums[ptr]
68+
# idx +=1
69+
# ptr +=1
70+
71+
# else:
72+
# idx +=1
73+
74+
# return ptr
75+
76+
idx = 0
77+
ptr = 0
78+
while idx < len(nums):
79+
if nums[idx] != nums[ptr]:
80+
ptr +=1
81+
curr = nums[ptr]
82+
nums[ptr] = nums[idx]
83+
nums[idx] = curr
84+
idx += 1
85+
else:
86+
idx += 1
87+
return ptr + 1

9_Palindrome_Number.py

+47
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
"""
2+
9. Palindrome Number:
3+
4+
Given an integer x, return true if x is a
5+
palindrome
6+
, and false otherwise.
7+
8+
9+
10+
Example 1:
11+
12+
Input: x = 121
13+
Output: true
14+
Explanation: 121 reads as 121 from left to right and from right to left.
15+
16+
Example 2:
17+
18+
Input: x = -121
19+
Output: false
20+
Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.
21+
22+
Example 3:
23+
24+
Input: x = 10
25+
Output: false
26+
Explanation: Reads 01 from right to left. Therefore it is not a palindrome.
27+
"""
28+
29+
class Solution(object):
30+
def isPalindrome(self, x):
31+
"""
32+
:type x: int
33+
:rtype: bool
34+
"""
35+
reverse = 0
36+
if (x < 0) or (x % 10 == 0 and x != 0):
37+
return False
38+
else:
39+
while (x > reverse):
40+
reverse = reverse*10 + x%10
41+
x /= 10
42+
43+
return x == reverse or x== reverse/10
44+
45+
46+
47+

0 commit comments

Comments
 (0)