![]() |
VOOZH | about |
Given a string str of size N, the task is to find the suffix array of the given string.
Note: A suffix array is a sorted array of all suffixes of a given string.
Examples:
Input: str = "prince"
Output: 4 5 2 3 0 1
Explanation: The suffixes are
0 prince 4 ce
1 rince Sort the suffixes 5 e
2 ince ----------------> 2 ince
3 nce alphabetically 3 nce
4 ce 0 prince
5 e 1 rinceInput: str = "abcd"
Output: 0 1 2 3
Approach: The methods of suffix array finding for any string are discussed here. In this article, the focus is on finding suffix array for strings with no repeating character. It is a simple implementation based problem. Follow the steps mentioned below to solve the problem:
Follow the illustration below for better understanding.
Illustration:
Consider string "prince":
Given below is the suffix table
char a b c d e f g h i j k l m n o p q r s t u v w x y z count 0 0 1 0 1 0 0 0 1 0 0 0 0 1 0 1 0 1 0 0 0 0 0 0 0 0 prefix 0 0 1 1 2 2 2 2 3 3 3 3 3 4 4 5 5 6 6 6 6 6 6 6 6 6 start 0 0 0 1 1 2 2 2 2 3 3 3 3 3 4 4 5 5 6 6 6 6 6 6 6 6 For char 'r' start value is 5 .
Implies substring (suffix) starting with char 'r' i.e. "rince" has rank 5 .
Rank is position in suffix array. ( 1 "rince" ) implies 5th position in suffix array ), refer first table.
Similarly, start value of char 'n' is 3 . Implies ( 3 "nce" ) 3rd position in suffix array .
Below is the implementation of the above approach
4 5 2 3 0 1
Time Complexity: O(N)
Auxiliary Space: O(N)