Problem Solution

1 solutions

  • 1
    @ 2024-04-01 22:04:53

    As we can sort the string in two different ways, so we will find two answers for two types of sorting and then will print the minimum of them.

    • Sorting in non-decreasing(ascending) order:

    lets say there are total x zeros in the string S. if we want to sort it in ascending order then all of x zeros must be in first x position such as(00011). Now we will count how many ones ('1') are present in first x position. lets say there are y ones in first x positions. so there must be y zeroes from x+1 to n th position of the string and we just need to make y number of swap to transfer all remaining y zeroes into first x positions. so the answer is y (answer1)

    • Sorting in non-increasing(descending) order:

    Lets say there are total x ones in the string S. if we want to sort it in descending order then all of x ones must be in first x position such as(11000).Now we will count how many zeros are present in first x position. lets say there are y zeros in first x position. so there must be y ones from x+1 to n-th position of the string and we just need to make y number of swap to transfer all ramaining y zeros into first x positions. so the answer is y (answer2)

    final answer will be min(ans1,ans2)

    time complexity: O(N)

  • 1

Information

ID
1016
Difficulty
5
Category
String_Processing , Sorting Click to Show
Tags
(None)
# Submissions
26
Accepted
13
Accepted Ratio
50%
Uploaded By