Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #User function Template for python3
- class Solution:
- #Function to arrange all letters of a string in lexicographical
- #order using Counting Sort.
- def countSort(self,arr):
- def get(x):
- return ord(x)-ord('a')
- n=len(arr)
- #find frequencies of each character
- count=[0 for i in range(26)]
- for i in arr:
- count[get(i)]+=1
- sum=count[0]
- #make cumulative frequency array
- for i in range(1,26):
- temp=count[i]
- count[i]+=sum
- sum+=temp
- #right rotate array by 1 step
- for i in range(25,-1,-1):
- count[i]=count[i-1]
- count[0]=0
- #resultant array where sorted text exists
- output=[None]*n
- for char in arr:
- index=count[get(char)]
- count[get(char)]+=1
- output[index]=char
- return "".join(output)
- # code here
- #{
- # Driver Code Starts
- #Initial Template for Python 3
- import atexit
- import io
- import sys
- _INPUT_LINES = sys.stdin.read().splitlines()
- input = iter(_INPUT_LINES).__next__
- _OUTPUT_BUFFER = io.StringIO()
- sys.stdout = _OUTPUT_BUFFER
- @atexit.register
- def write():
- sys.__stdout__.write(_OUTPUT_BUFFER.getvalue())
- if __name__ == '__main__':
- test_cases = int(input())
- for cases in range(test_cases) :
- n = int(input())
- arr = str(input())
- ob = Solution()
- print(ob.countSort(arr))
- # } Driver Code Ends
Add Comment
Please, Sign In to add comment