Array ( [0] => [1] => questions [2] => HackwithInfy-Previous-Questions [3] => Run-length-encoding ) Strings | Run length encoding | THE INQUISITIVE





Run length encoding

LEVEL:Beginner

Description

Given a string K. You have to print the occurrences of each character in given string.

Input Format

First line contains the string K.

Output Format

Print the occurrences of characters in given string.


Example 1:

Input
maximum
Output
m3a1x1i1u1
Example 2:

Input
knowledge is divine
Output
k1n2o1w1l1e3d2g1i3s1v1
Example 3:

Input
he is my favourite hero
Output
h2e3i2s1m1y1f1a1v1o2u1r2t1

oops

Login to see Discussion




Approach

Approach 1: Using two loops

step-i) create an empty string answer
step-ii) create a character visited of length equal to length of string
step-iii) assign 0 to k
step-iv) assign 0 to i
step-v) assign 0 to count and false to is_there
step-vi)assign 0 to j
step-vii) is character at i of string is equal to character at j of visited then make is_there to true
step-viii) repeat step vii till j is less than K
step-ix)if is_there is false assign character at index i of string to visited array at postion k and increment the k
step-x) traverse the entire string and count how many no of occurences of characters are present in the string
step-xi)concatinate character and it's occurences to the string answer
step-xii) repeat steps v to xi till i is less than the length of the string
step-xiii) return answer

Time Complexity: O(n^2)
Space Complexity: O(n)

Approach 2: using hashmap

step-i) create a string builder answer
step-ii) create a hasmap with character as keys and Integer as values
step-iii)convert given string to character array
step-iv) traverse through the character array and check if the character is present in keys of hashmap
step-v) if it is present in keys then increment its value by one
step-vi) if it is not present in keys then add that character as key and 1 as it's value
step-vii)now append both keys and it's respective values to the string builder that was created earlier
step-viii)return the string builder which is answer

Time Complexity: O(n)
Space Complexity:O(n)


Note :

Let us know if you can come up with a better approach, mail us at support@theinquisitive.in Your approach will be reviewed and posted with credits to you.

oops

Login to see Solution