Advertisement
Kali_prasad

A20250415_flipkart_strings

Apr 15th, 2025
298
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.28 KB | None | 0 0
  1. '''
  2. A20250415_flipkart_strings
  3.  
  4. given you a string
  5. need to make it lexographically smallest string by doing
  6. one operation
  7.  
  8. operation pick any character and place it anywhere else
  9.  
  10.  
  11. -----------------------------------------------------------------------------------------------------
  12. important thing to be noted is
  13.  
  14. the main nature of lexographic is ,the first characters in the string should be as small as possible
  15. how do we know where to place
  16. lets have a reference of smallest lexographic string
  17. which is obtained by sorting string characters
  18. now compare it with every char of original
  19. when there is a mismatch we know the position now at this point print the ideal character and
  20. from now on continue printing the other
  21. however if you encountered ideal character again through the original string,if it is the last occurance skip it
  22.  
  23. skipping the last occarance instead of first occurance in problematic part
  24. will make us to have the smallest possible lexographic string
  25.  
  26. say you have
  27. BCCCAADAAD //given
  28. AAAABCCCDD //sorted
  29.  
  30. ABCCCAADAD //ans when we picked right most A
  31. ABCCCADAAD //ans when we picked left most A
  32.  
  33. so it is evident to choose the right most than the left most A
  34.  
  35. -----------------------------------------------------------------------------------------------------
  36. input -
  37. BCCCAADAAD
  38.  
  39. output -
  40. ABCCCADAAD
  41.  
  42. '''
  43.  
  44. givenStringArr = list(input())
  45. sortedStringArr = sorted(givenStringArr)
  46. fMap = {}
  47. for char in givenStringArr:
  48.     if char in fMap:
  49.         fMap[char] += 1
  50.     else:
  51.         fMap[char] = 1
  52. firstMismatchFound = False
  53. idealChar = '#'
  54. for i in range(len(givenStringArr)):
  55.     # print('givenStringArr ',givenStringArr[i])
  56.     # print('sortedStringArr ',sortedStringArr[i])
  57.     if not firstMismatchFound and givenStringArr[i] == sortedStringArr[i]:
  58.         print(givenStringArr[i],end='')
  59.         fMap[givenStringArr[i]] -= 1
  60.     elif not firstMismatchFound and givenStringArr[i] != sortedStringArr[i]:
  61.         firstMismatchFound = True
  62.         print(sortedStringArr[i],end='')
  63.         fMap[sortedStringArr[i]] -= 1
  64.         print(givenStringArr[i],end='')
  65.         fMap[givenStringArr[i]] -= 1
  66.     elif firstMismatchFound and fMap[givenStringArr[i]] > 0:
  67.         print(givenStringArr[i],end='')
  68.         fMap[givenStringArr[i]] -= 1
  69.  
  70.  
  71.  
  72.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement