Skip to content

Commit

Permalink
Adding solutions of 200, 203, 206, 208, 210 and top interview questions
Browse files Browse the repository at this point in the history
  • Loading branch information
Garvit244 committed May 12, 2018
1 parent 5748a12 commit 4ae07ef
Show file tree
Hide file tree
Showing 21 changed files with 755 additions and 2 deletions.
5 changes: 4 additions & 1 deletion 100-200q/125.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,4 +25,7 @@ def numDistinct(self, s, t):
dp[r][c] = dp[r-1][c]
if s[r-1] == t[c-1]:
dp[r][c] += dp[r-1][c-1]
return dp[row][col]
return dp[row][col]

# Time: O(N^2)
# Space: O(N^2)
62 changes: 62 additions & 0 deletions 100-200q/127.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
'''
Given two words (beginWord and endWord), and a dictionary's word list, find the length of shortest transformation sequence from beginWord to endWord, such that:
Only one letter can be changed at a time.
Each transformed word must exist in the word list. Note that beginWord is not a transformed word.
Note:
Return 0 if there is no such transformation sequence.
All words have the same length.
All words contain only lowercase alphabetic characters.
You may assume no duplicates in the word list.
You may assume beginWord and endWord are non-empty and are not the same.
Example 1:
Input:
beginWord = "hit",
endWord = "cog",
wordList = ["hot","dot","dog","lot","log","cog"]
Output: 5
Explanation: As one shortest transformation is "hit" -> "hot" -> "dot" -> "dog" -> "cog",
return its length 5.
'''

class Solution(object):
def ladderLength(self, beginWord, endWord, wordList):
"""
:type beginWord: str
:type endWord: str
:type wordList: List[str]
:rtype: int
"""
d = {}
for word in wordList:
for i in range(len(word)):
s = word[:i] + "_" + word[i+1:]
if s in d:
d[s].append(word)
else:
d[s] = [word]

queue, visited = [], set()
queue.append((beginWord, 1))
while queue:
word, steps = queue.pop(0)
if word not in visited:
visited.add(word)

if word == endWord:
return steps
else:
for index in range(len(word)):
s = word[:index] + "_" + word[index+1:]
neigh_words = []
if s in d:
neigh_words = d[s]

for neigh in neigh_words:
if neigh not in visited:
queue.append((neigh, steps+1))
return 0
31 changes: 31 additions & 0 deletions 100-200q/128.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
'''
Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
Your algorithm should run in O(n) complexity.
Example:
Input: [100, 4, 200, 1, 3, 2]
Output: 4
Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4.
'''

class Solution(object):
def longestConsecutive(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
result = 0
nums = set(nums)

for num in nums:
if num-1 not in nums:
curr = num
length = 1

while curr+1 in nums:
curr += 1
length += 1
result = max(result, length)
return result
49 changes: 49 additions & 0 deletions 100-200q/129.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
'''
Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number.
An example is the root-to-leaf path 1->2->3 which represents the number 123.
Find the total sum of all root-to-leaf numbers.
Note: A leaf is a node with no children.
Example:
Input: [1,2,3]
1
/ \
2 3
Output: 25
Explanation:
The root-to-leaf path 1->2 represents the number 12.
The root-to-leaf path 1->3 represents the number 13.
Therefore, sum = 12 + 13 = 25.
'''

# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None

class Solution(object):
def sumNumbers(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if not root:
return 0

def dfs(root, num, total):
if not root:
return total
num = num*10 + root.val
if not root.left and not root.right:
total += num
return total

return dfs(root.left, num) + dfs(root.right, num)

return dfs(root, 0, 0)
26 changes: 26 additions & 0 deletions 100-200q/130.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
'''
Given a 2D board containing 'X' and 'O' (the letter O), capture all regions surrounded by 'X'.
A region is captured by flipping all 'O's into 'X's in that surrounded region.
Example:
X X X X
X O O X
X X O X
X O X X
After running your function, the board should be:
X X X X
X X X X
X X X X
X O X X
'''

class Solution(object):
def solve(self, board):
"""
:type board: List[List[str]]
:rtype: void Do not return anything, modify board in-place instead.
"""

25 changes: 25 additions & 0 deletions 100-200q/131.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
'''
Given a string s, partition s such that every substring of the partition is a palindrome.
Return all possible palindrome partitioning of s.
'''

class Solution(object):
def partition(self, s):
result = []
def valid(s):
for i in range(len(s)/2):
if s[i] != s[-(i+1)]:
return False
return True

def partitionRec(curr, s, i):
if i == len(s):
result.append(curr)
else:
for j in range(i, len(s)):
if valid(s[i:j+1]):
partitionRec(curr + [s[i:j+1]], s, j+1)

partitionRec([], s, 0)
return result
28 changes: 28 additions & 0 deletions 100-200q/134.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
'''
There are N gas stations along a circular route, where the amount of gas at station i is gas[i].
You have a car with an unlimited gas tank and it costs cost[i] of gas to travel from station i to its next station (i+1). You begin the journey with an empty tank at one of the gas stations.
Return the starting gas station's index if you can travel around the circuit once in the clockwise direction, otherwise return -1.
'''

class Solution(object):
def canCompleteCircuit(self, gas, cost):
"""
:type gas: List[int]
:type cost: List[int]
:rtype: int
"""
start, curr_sum, total_sum =0, 0, 0
for index in range(len(gas)):
diff = gas[index] - cost[index]
total_sum += diff
curr_sum += diff

if curr_sum < 0:
start = index + 1
curr_sum = 0

if total_sum >= 0:
return start
return -1
2 changes: 1 addition & 1 deletion 100-200q/139.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,5 +25,5 @@ def wordBreak(self, s, wordDict):
for j in range(i, -1, -1):
if dp[j] and s[j:i+1] in wordDict:
dp[i+1] = True
wordBreak
break
return dp[len(s)]
30 changes: 30 additions & 0 deletions 100-200q/141.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
'''
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
'''

# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None

class Solution(object):
def hasCycle(self, head):
"""
:type head: ListNode
:rtype: bool
"""

if not head:
return False

slow, fast = head,head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow == fast:
return True
return False
62 changes: 62 additions & 0 deletions 100-200q/148.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
'''
Sort a linked list in O(n log n) time using constant space complexity.
Example 1:
Input: 4->2->1->3
Output: 1->2->3->4
'''

# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None

class Solution(object):
def sortList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""

if not head or not head.next:
return head

slow, fast = head, head.next

while fast.next and fast.next.next:
slow = slow.next
fast = fast.next.next

head1, head2 = head, slow.next
slow.next = None
head1 = self.sortList(head1)
head2 = self.sortList(head2)
head = self.merge(head1, head2)
return head

def merge(self, head1, head2):
if not head1:
return head2
if not head2:
return head1

result = ListNode(0)
p = result

while head1 and head2:
if head1.val <= head2.val:
p.next = ListNode(head1.val)
head1 = head1.next
p = p.next
else:
p.next = ListNode(head2.val)
head2 = head2.next
p = p.next

if head1:
p.next = head1
if head2:
p.next = head2
return result.next
Loading

0 comments on commit 4ae07ef

Please sign in to comment.