Iam_Sandeep

counting sort for strings of letters

Sep 2nd, 2021 (edited)
308
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.52 KB | None | 0 0
  1. #User function Template for python3
  2.  
  3. class Solution:
  4.     #Function to arrange all letters of a string in lexicographical
  5.     #order using Counting Sort.
  6.     def countSort(self,arr):
  7.         def get(x):
  8.             return ord(x)-ord('a')
  9.         n=len(arr)
  10.         #find frequencies of each character
  11.         count=[0 for i in range(26)]
  12.         for i in arr:
  13.             count[get(i)]+=1
  14.         sum=count[0]
  15.         #make cumulative frequency array
  16.         for i in range(1,26):
  17.             temp=count[i]
  18.             count[i]+=sum
  19.             sum+=temp
  20.         #right rotate array by 1 step
  21.         for i in range(25,-1,-1):
  22.             count[i]=count[i-1]
  23.         count[0]=0
  24.         #resultant array where sorted text exists
  25.         output=[None]*n
  26.         for char in arr:
  27.             index=count[get(char)]
  28.             count[get(char)]+=1
  29.             output[index]=char
  30.         return "".join(output)
  31.            
  32.        
  33.         # code here
  34.  
  35. #{
  36. #  Driver Code Starts
  37. #Initial Template for Python 3
  38.  
  39. import atexit
  40. import io
  41. import sys
  42.  
  43. _INPUT_LINES = sys.stdin.read().splitlines()
  44. input = iter(_INPUT_LINES).__next__
  45. _OUTPUT_BUFFER = io.StringIO()
  46. sys.stdout = _OUTPUT_BUFFER
  47.  
  48. @atexit.register
  49.  
  50. def write():
  51.     sys.__stdout__.write(_OUTPUT_BUFFER.getvalue())
  52.  
  53. if __name__ == '__main__':
  54.     test_cases = int(input())
  55.     for cases in range(test_cases) :
  56.         n = int(input())
  57.         arr = str(input())
  58.         ob = Solution()
  59.         print(ob.countSort(arr))
  60.  
  61. # } Driver Code Ends
Add Comment
Please, Sign In to add comment