Skip to main content

Posts

Showing posts from 2021

Adjacency List in a Graph

   from collections import defaultdict graph=defaultdict(list) v,e=map(int,input().split()) for i in range(e):     u,v=map(str,input().split())     graph[u].append(v)     graph[v].append(u)      for i in graph:     print(i,"->",graph[i]) Input: 7 9 A B A C A F C E C F C D D E D G G F Output: F -> ['A', 'C', 'G'] C -> ['A', 'E', 'F', 'D'] G -> ['D', 'F'] D -> ['C', 'E', 'G'] A -> ['B', 'C', 'F'] E -> ['C', 'D'] B -> ['A']       

Adjacency List in a Graph

   from collections import defaultdict graph=defaultdict(list) v,e=map(int,input().split()) for i in range(e):     u,v=map(str,input().split())     graph[u].append(v)     graph[v].append(u)      for i in graph:     print(i,"->",graph[i]) Input: 7 9 A B A C A F C E C F C D D E D G G F Output: F -> ['A', 'C', 'G'] C -> ['A', 'E', 'F', 'D'] G -> ['D', 'F'] D -> ['C', 'E', 'G'] A -> ['B', 'C', 'F'] E -> ['C', 'D'] B -> ['A']       

Find the single occurence of a element in the list of elements with twice repeative

  """ n=[23, 2, 2, 24, 7, 23, 5, 24, 5] printing  res n[i] res^n[i] 23  2       21 21  2       23 23  24      15 15  7       8 8   23      31 31  5       26 26  24      2 2   5       7 so the res = 7  we know that n^n=0 where n^0 = n this is how the repeated elements are vanised """ def find(n):     res=n[0]          for i in range(1,len(n)):         res=res^ n[i]     return res n=list(map(int,input().split())) s=find(n) print(s)

Check the whether the kth bit from right is SET ?

  #  #lets see n=6 # #in binary 6 is 101 =>6  #lets check at 1 from right # 1<<(1-1) => its left shift so it multiplies 1 with 2**(1-1) thats 2**0  # so 2**0 is 1  #1*1=>1 #in binary 6 is 101 #in binary 1 is 001 # #so bitwise & = 001 =>1 SET # # Ex2 #In binary 6 is 101 =>6  #lets check at 2 from right # 1<<(2-1) => its left shift so it multiplies 1 with 2**(2-1) thats 2**1 # so 2**1 is 2  #1*2=>2 #in binary 6 is 101 #in binary 1 is 010 # #so bitwise & = 000 =>0 NOT SET def kthbit(n,k):          if n&(1<<(k-1)):         print("SET")     else:         print("Not Set")              n,k=map(int,input().split()) print("The bit in ",bin(n)[2:],"at",k,"from right is") kthbit(n,k)

Once's in Binary Representation of a Number

  #  #lets see n=7 #count =0 #in binary 7 is 111 =>7 count =1 #in binary 6 is 101 # #so bitwise & = 101 =>6 count =2 #in binary 6 is 101 #in binary 5 is 100 # #so bitwise & = 100 =>5 count =3 #in binary 5 is 100 #in binary 4 is 011 # #so bitwise & = 000 =>0 def onces(n):     cnt=0      while(n):         cnt+=1         n=n&(n-1)          return cnt                     n=int(input()) print("Onces in ",bin(n)[2:],"is",onces(n))  

Find the even odd using bitwise

  We can use bitwise And to check even or odd if n is a number then  n&1 result the 1 else result the 0 def oddeven(n):     if n&1==1:         print("ODD")     else:         print("EVEN")           n=int(input()) oddeven(n)

Print all Prime numbers Using Sieve of Eratosthenes

  from math import sqrt def allPrime(n):     l=[True]*(n+1)     l[0]=False     l[1]=False     for i in range(2,int(sqrt(n))+1):         if l[i]==True:             for j in range(i*i,n+1,i):                 l[j]=False                      for i in range(n+1):         if l[i]==True:             print(i,end=" ")   n=int(input()) allPrime(n)

Is it a Prime?

  from math import sqrt def isPrime(n):     if n==0 or n==1:         return False     if n==2 or n==3:         return True     if n%2==0 or n%3==0:         return False     for i in range(5,int(sqrt(n))+1):         if n%i==0 or n%(i+2)==0:             return False     return True      n=int(input()) print("Is",n,"a Prime",isPrime(n))   

Find the Divisors of a number

  from math import sqrt def div(n):     div1=set()     for i in range(1,int(sqrt(n))+1):         if n%i==0:             div1.add(i)             div1.add(n//i)     return sorted(list(div1)) n=int(input()) print("The divisors of ",n,"is",*div(n))  

GCD and LCM using Euclid algo

  #product of two number = lcm * gcd  def gcd(a,b):     if a==0:         return b     return gcd(b%a,a) def lcm(a,b):     prod=a*b      hcf=gcd(a,b)     return prod//hcf a,b=map(int,input().split()) print("lcm: ",lcm(a,b)," ","gcd: ",gcd(a,b))  

Diamond Pattern

          Diamond:  n=int(input()) t=n k=0 while(t!=0):                    print("*"*(t-1),end="")     print("."*(n-t+1+k),end="")     print("*"*(t-1),end="")     print()     t-=1     k+=1      t=1 k=((n-1)*2)-1 while(t!=n):                    print("*"*(t),end="")     print("."*(k),end="")     print("*"*(t),end="")     print()     t+=1     k-=2 output:   

Maximum Unsorted Subarray Asked in: Amazon Microsoft

  You are given an array (zero-indexed) of   N   non-negative integers,   A 0 ,   A 1   ,…,   A N-1 . Find the minimum sub-array  A l ,  A l+1 ,…,  A r  so if we sort(in ascending order) that sub-array, then the whole array should get sorted. If  A  is already sorted, output  -1 . Example : Input 1: A = [1, 3, 2, 4, 5] Return: [1, 2] Input 2: A = [1, 2, 3, 4, 5] Return: [-1] In the above example(Input 1), if we sort the subarray  A 1 ,  A 2 , then whole array  A  should get sorted. ut Solution: class Solution:     # @param A : list of integers     # @return a list of integers     def subUnsort(self, A):         s_a=sorted(A)         if A==s_a:             return [-1]         l=len(A)         minI=-1         maxI=l         f1=True         f2=True         for i in range(l):             if A[i]!=s_a[i] and i>minI and f1==True:                 minI=i                 f1=False             if A[l-i-1]!=s_a[l-i-1] and l-1-i<maxI and f2==True:                 maxI=l-i-1              

Max Distance Asked in: Google Amazon Microsoft

  Problem Description Given an array  A  of integers, find the maximum of  j - i  subjected to the constraint of  A[i] <= A[j] . Input Format First and only argument is an integer array A. Output Format Return an integer denoting the maximum value of j - i; Example Input Input 1: A = [3, 5, 4, 2] Example Output Output 1: 2 Example Explanation Explanation 1: Maximum value occurs for pair (3, 4). Solution: class Solution:     # @param A : tuple of integers     # @return an integer     def maximumGap(self, A):         n=len(A)             R = [0] * n              R[n - 1] = A[n - 1]          for j in range(n - 2, -1, -1):              R[j] = max(A[j], R[j + 1]);               i = 0;j=0         diff = -1         while (j < n and i < n):              if (A[i] <= R[j]):                  diff = max(diff, j - i)                  j+=1             else:                  i+=1              return diff                                 Screenshot:

Rotate Matrix Asked in: Google Facebook Amazon

  You are given an n x n 2D matrix representing an image. Rotate the image by 90 degrees (clockwise). You need to do this in place. Note that if you end up using an additional array, you will only receive partial score. Example: If the array is [ [1, 2], [3, 4] ] Then the rotated array becomes: [ [3, 1], [4, 2] ] Solution: class Solution:     # @param A : list of list of integers     # @return the same list modified     def rotate(self, A):         l = len(A)         for i in range(l//2):             A[i], A[l-i-1] = A[l-i-1], A[i]         ans = [[A[j][i] for j in range(l)] for i in range(len(A[0]))]         return ans Screenshot:

Find Duplicate in Array Asked in: Amazon VMWare Riverbed

  Given a read-only array of n + 1 integers between 1 and n, find one number that repeats in linear time using less than O(n) space and traversing the stream sequentially O(1) times. Sample Input: [3 4 1 4 1] Sample Output: 1 If there are multiple possible answers ( like in the sample case above ), output any one. If there is no duplicate, output -1 Solution class Solution:     # @param A : tuple of integers     # @return an integer     def repeatedNumber(self, A):         l_A=len(A)         s_A=set(A)         d={}         l_s=len(s_A)         if l_A==l_s:             return -1         for i in A:             if i in d:                 d[i]+=1             else:                 d[i]=1         for i,j in d.items():             if j>1:                 return i          Screenshot:

Flip Asked in: VMWare

  You are given a binary string( i.e.   with characters   0   and   1 ) S consisting of characters S 1 , S 2 , …, S N . In a single operation, you can choose two indices L and R such that 1 ≤ L ≤ R ≤ N and flip the characters S L , S L+1 , …, S R . By flipping, we mean change character   0   to   1   and vice-versa. Your aim is to perform ATMOST one operation such that in final string number of  1 s is maximised. If you don’t want to perform the operation, return an empty array. Else, return an array consisting of two elements denoting L and R. If there are multiple solutions, return the lexicographically smallest pair of L and R. Notes : Pair (a, b) is lexicographically smaller than pair (c, d) if a < c or, if a == c and b < d. For example, S = 010 Pair of [L, R] | Final string _______________|_____________ [1 1] | 110 [1 2] | 100 [1 3] | 101 [2 2] | 000 [2 3] | 001 We see that two pairs [1, 1] and [1, 3] give same number of 1s in f

Add One To Number Asked in: Google Microsoft

  Given a non-negative number represented as an array of digits, add 1 to the number ( increment the number represented by the digits ). The digits are stored such that the most significant digit is at the head of the list. Example: If the vector has  [1, 2, 3] the returned vector should be  [1, 2, 4] as  123 + 1 = 124 .   NOTE:  Certain things are intentionally left unclear in this question which you should practice asking the interviewer. For example, for this problem, following are some good questions to ask : Q :  Can the input have 0’s before the most significant digit. Or in other words, is  0 1 2 3  a valid input? A :  For the purpose of this question,  YES Q :  Can the output have 0’s before the most significant digit? Or in other words, is  0 1 2 4  a valid output? A :  For the purpose of this question,  NO . Even if the input has zeroes before the most significant digit. Solution: class Solution:     # @param A : list of integers     # @return a list of integers     def plusO