Google_imp_medium Flashcards
Encode and Decode TinyURL
use the random function to
generate a 6 letter word which is a combination of lower and upper and digits and return as shortcode
when longurl is inputted to encode if longurl in dict1 return shorturl
else then call random and get 6 digit word if that word is not in dict then append that with prefix and push to dict1 with value and return prefix+shortcode
in decode return dict1(shorturl)
decode(encode(longurl))
resulting is again longurl
import random import string class Codec: def \_\_init\_\_(self): self.dict1={}
def get_random(self): return ''.join(random.choice(string.ascii_uppercase+string.ascii_lowercase+string.digits) for _ in range(6))
def encode(self, longUrl): """Encodes a URL to a shortened URL.
:type longUrl: str :rtype: str """ prefix="http://tinyurl.com" for k,v in self.dict1.items(): if v==longUrl: return prefix+str(k) tiny_code=self.get_random()
while tiny_code in self.dict1.keys(): tiny_code=self.get_random() self.dict1[prefix+str(tiny_code)]=longUrl return prefix+str(tiny_code)
def decode(self, shortUrl): """Decodes a shortened URL to its original URL.
:type shortUrl: str :rtype: str """ return self.dict1[shortUrl]
Queue Reconstruction by Height
need to sort in decreasing order by height and increasing order by number of persons
class Solution(object): def reconstructQueue(self, people): res=[] for p in sorted(people, key=lambda x :(-x[0],x[1])): res.insert(p[1], p) return res
Wiggle Sort
reorder it in-place such that nums[0] <= nums[1] >= nums[2] <= nums[3]….
sort the nums
fill the odd places of nums by poping them from end until len(nums) range
nums.sort()
for i in range(1,len(nums),2):
nums.insert(i,nums.pop())
Daily Temperatures
start from last index
if stack then find if there is any element greater than this in stack by popping and once if it is found then subtract that index with this index if found ans store it in index of element place ins ans array.
now append this element index to stack
finally return ans
class Solution: def dailyTemperatures(self, T): """ :type T: List[int] :rtype: List[int] """
ans=[0]*len(T) stack=[] for i in range(len(T)-1,-1,-1): while stack and T[i]>=T[stack[-1]]: stack.pop() if stack: ans[i]=stack[-1]-i stack.append(i) return ans
Generate Parentheses
if n=3 then ()()() or ()(()) or ….is ans
backtrack
ans=[] def backtrack(s='',left=0,right=0): if len(s)==2*n: ans.append(s) return if left
Game of life
According to the Wikipedia’s article: “The Game of Life, also known simply as Life, is a cellular automaton devised by the British mathematician John Horton Conway in 1970.”
Given a board with m by n cells, each cell has an initial state live (1) or dead (0). Each cell interacts with its eight neighbors (horizontal, vertical, diagonal) using the following four rules (taken from the above Wikipedia article):
Any live cell with fewer than two live neighbors dies, as if caused by under-population.
Any live cell with two or three live neighbors lives on to the next generation.
Any live cell with more than three live neighbors dies, as if by over-population.
Any dead cell with exactly three live neighbors becomes a live cell, as if by reproduction.
class Solution: def gameOfLife(self, board): """ :type board: List[List[int]] :rtype: void Do not return anything, modify board in-place instead. """ r=len(board) c=len(board[0])
x=[-1,-1,-1,0,0,1,1,1] y=[0,1,-1,-1,1,0,1,-1]
for i in range(r): for j in range(c): count=0 for k in range(8): nx=i+x[k] ny=j+y[k]
if nx>=0 and nx=0 and ny 3: newstate = 0 board[i][j] = board[i][j] | (newstate << 1) for i in range(r): for j in range(c): board[i][j] = board[i][j] >> 1
Meeting Rooms II
make a sorted list of start times and endtimings
loop through start timings
if you find start timings> end timing then room is emptied and now comapre with next meeting end timing.
if not increase rooms by 1 an start ptr by 1
class Solution: def minMeetingRooms(self, intervals): """ :type intervals: List[Interval] :rtype: int """ room=0 if len(intervals)==0: return 0 starttimings=sorted([i.start for i in intervals]) endtimings=sorted([i.end for i in intervals])
str_ptr=end_ptr=0 while str_ptr=endtimings[end_ptr]:
room=room-1 end_ptr+=1 room=room+1 str_ptr+=1 return room
Fruit Into Baskets
start with starting tree and collect fruits of type and maintain a ductionary of type and count.
if you find any time this dict>2 length then move n i value so that you are deleting starting values
maxcount alwayd maintain max of length of list (j=i+1) at any point of time when two type of fruits available.
max_count=0 i=0 basket={} for j,x in enumerate(tree): if x in basket: basket[x]+=1 else: basket[x]=1 while len(basket)>2: basket[tree[i]]-=1
if basket[tree[i]]==0: del basket[tree[i]] i=i+1 max_count = max(max_count, j - i + 1) return max_count
Find Peak Element(logn time complexity)
here we find mid and compare with mid+1 if slopw is decreasing then increasing will be in left so r=mid
else if slope is increasing then decreasing will be in right hence l =mid+1
l,r=0,len(nums)-1 while lnums[mid+1]: # slope is slanting so peak must be in left r=mid else: l=mid+1 return l
Search a 2D Matrix II
start with 1st row and last column
if value ==target : return True elif value>target row+1 else . col-1
if len(matrix)==0: return False row=0 col=len(matrix[0])-1
while row=0:
val=matrix[row][col] if val==target: return True elif target>val: row=row+1 else: col=col-1 return False
Perfect Squares
append all perfect squares less than n
then looping through this and n
fill the result array which is of size n+1
using
arr1[j]=min(arr1[j],1+arr1[j-psquare[i]])
if n==1: return 1 if n==0: return psquare=[] for i in range(1,n): if i*i>n: break psquare.append(i*i) max_sum=float('inf') arr1=[max_sum for i in range(n+1)] arr1[0]=0
for i in range(len(psquare)): for j in range(n+1): if j>=psquare[i]: arr1[j]=min(arr1[j],1+arr1[j-psquare[i]]) return arr1[-1]
Phone Number
class Solution: def \_\_init\_\_(self): self.digitmap={ "2": ["a", "b", "c"], "3": ["d", "e", "f"], "4": ["g", "h", "i"], "5": ["j", "k", "l"], "6": ["m", "n", "o"], "7": ["p", "q", "r", "s"], "8": ["t", "u", "v"], "9": ["w", "x", "y", "z"] }
def letterCombinations(self, digits): """ :type digits: str :rtype: List[str] """ if len(digits)==0: return [] results=[] def dfs(digits,i,word): if i==len(digits): results.append(word) return for c in self.digitmap[digits[i]]: word=word+c dfs(digits,i+1,word) word=word[:-1] dfs(digits,0,'') return results
Number of Islands
class Solution: def numIslands(self, grid): """ :type grid: List[List[str]] :rtype: int """ if len(grid)==0: return 0 x=[-1,0,0,1] y=[0,1,-1,0]
r=len(grid) c=len(grid[0]) count1=0 def dfs(i,j,grid,x,y): grid[i][j]='#' for k in range(4): nx=i+x[k] ny=j+y[k] if nx>=0 and nx=0 and ny
Longest Absolute File Path
fill the stack by counts of strings until . extension is found. once it is found count te stack len and . file length
while loop i used when u go into sublevels and if u find a parallel level subsirectors with the help of count u will pop o stack and maintain the count
stack,max_len=[],0
for i in input.split('\n'): while stack and len(stack)>i.count('\t'): stack.pop() if i.count('.')==0: stack.append(len(i.strip('\t'))+1) else: max_len=max(max_len,sum(stack)+len(i.strip('\t'))) return max_len
Merge Intervals
k=[]
for i in sorted(intervals, key=lambda i: i.start):
print(i)
if len(k)==0: k.insert(len(k),i) elif k[-1].end>=i.start: k[-1].end=max(k[-1].end,i.end) else: k.insert(len(k),i) return k