Friday, April 22, 2022

Coding interview questions: Python

Hello, 

Here in this post I will solve some basic coding interview question. This time I used python. Yes its cool.

Find second largest number in given array?

input: [1,2,0,9,8] output: 8
input: [0,1,-1,-2] output: 0
input: [3] output: 
input: [] output: 
def findSecondLargestNumber(arr_list):
  largest = None
  secondL = None
  for i in arr_list:
    if largest == None:
      largest = i
    elif i > largest:
      secondL = largest
      largest = i
    elif secondL == None:
      secondL = i
    elif i > secondL:
      secondL = i
    
  print(secondL)

findSecondLargestNumber([0-11])

Find given two string inputs are reverse?
input: "ABC", "CBA" Output : True
input: "ABC", "cBA" Output : False
input: "ABC", "BCA" Ouput: False

def stringReverse(string1string2):
  for i in range(len(string1)):
    i1 = len(string2) - i -1;
    if(string1[i] != string2[i1]):
      return False
  return True 

stringReverse('ABC''cba')

Find given two string number, first input is greater than 2nd without using (int) convert?

Input: "1234" "4321" Ouput: False
Input: "1234" "321" Ouput: True
Input: "1234" "1234" Ouput: False

def largerthan(str1str2):
  if(len(str1) == len(str2)):
    for i in range(len(str1)):
      if str1[i] == str2[i]:
        continue
      elif str1[i] > str2[i]:
        return True
      else:
        return False
    return False
  elif len(str1) > len(str2):
    return True
  else:
    return False

largerthan('723''234')

Find rooks are safe in chessboard, if u don't know what is that? Don't worry, in chessboard rook can move vertical and horizontal line, if any rook block this we then moving rook will kill that?

For testing purpose I am using 4*4 board input instead of 8*8
Input: [[1,0,0,0],[0,1,0,0],[0,0,0,0],[0,0,0,1]] Output: True
Input: [[1,0,0,0],[0,1,0,0],[0,1,0,0],[0,0,0,1]] Output: False (because array[1,1] and array[2,1] are in same vertical line,
so the rooks are not safe)

def rookSafe(arr):
  for i in range(len(arr)):
    countRow = 0;
    countCol = 0;
    for j in range(len(arr)):
      countRow += arr[i][j]
      countCol += arr[j][i]
      if countCol > 1 or countRow > 1:
        return False
  return True

rookSafe([[1,0,0,0],[0,1,0,0],[0,0,0,0],[0,0,0,1]])


Java solution will be post soon!!👀

Thank you.

No comments:

Post a Comment