Minimum Coin Flips Amazon OA 2022

Page Contents

Minimum Coin Flips Amazon OA

Given the initial sequence of a coins, find the minimum number of coins that can be flipped to obtain a beautiful sequence. All head facing coins or tails facing coins sequence is also valid.

Input : THHHTH
Output : 2
Explanation : flip first and last coin to obtain the sequence.

Time Complexity : 0(N)

Space Complexity : 0(N)

Minimum Coin Flips Amazon OA
Minimum Coin Flips Amazon OA

SOLUTION

Program : Minimum Coin Flips Amazon OA Solution in Python

Lets see how can we solve this question “Minimum Coin Flips Amazon OA”.

  1. find the counts of “T” to the left of each element, store in a list
  2. find the counts of “H” to the right of each element, store in a list
  3. Ideally, we want all “H” to the left and all “T” to the right i.e “HHHTT”. So identifying all the “H” to the right and all the “T” to the left for any index tells us the number of swaps needed across that index.
    e.g S = “TTTTHHH” , say at index 3, which is “T”, there are 3 “T” to the left and 3 “H” to the right, so the total swaps is 3+ 3= 6. Repeat for each index and return the minimum
  4. Find the min of the sum of both lists for each element ,that is the answer
def func(string):
    
    Tleft = [0]* len(string)
    Hright = [0]*len(string)
    
    result = len(string)
    
    # iterate i from i = 1 since Tleft[0] is always 0
    
    for i in range(1, len(string)):
      if string[i-1] == "T":
          Tleft[i] = Tleft[i-1] + 1
      else:
          Tleft[i] = Tleft[i-1]
    
    #iterate from 2nd to last element since Hright[lastindex] is always 0
    
    for i in range(len(string)-2,-1,-1):
      if string[i+1] == "H":
          Hright[i] = Hright[i+1]+ 1
      else :
          Hright[i] = Hright[i+1]
    
    for i in range(len(string)):
         result = min(result, Tleft[i]+ Hright[i])
    #Using if condition to make sure if the given string is already in correct format like "HHTTT" all Head's on right and Tail's on left.
    if result!=0:
        return result
    return 1
#Taking input
s=input()
print(func(s))

Now as we have achieved the solution for Minimum Coin Flips Amazon OA Solution, there are few more questions similar to this logic which gives output in terms of 0’s and 1’s use the same logic approach to solve those questions.

Related: Amazon OA Online Assessment 2021 Questions and Answers

Leave a Comment

18 + 5 =