Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on String
  • Practice String
  • MCQs on String
  • Tutorial on String
  • String Operations
  • Sort String
  • Substring & Subsequence
  • Iterate String
  • Reverse String
  • Rotate String
  • String Concatenation
  • Compare Strings
  • KMP Algorithm
  • Boyer-Moore Algorithm
  • Rabin-Karp Algorithm
  • Z Algorithm
  • String Guide for CP
Open In App
Next Article:
Count of all unique substrings with non-repeating characters
Next article icon

Find the Suffix Array of given String with no repeating character

Last Updated : 24 Feb, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

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 rince

Input: 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:

  • Count occurrence of each character.
  • Find prefix sum of it.
  • Find start array by start[0] = 0, start[i+1] = prefix[i] for all i > 0 .
  • Find start array containing the index of the substring (suffix) with starting character of the respective column.

Follow the illustration below for better understanding.

Illustration:

Consider string "prince":
Given below is the suffix table 

charabcdefghijklmnopqrstuvwxyz
count00101000100001010100000000
prefix00112222333334455666666666
start00011222233333445566666666

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

C++
// C++ code to implement above approach #include <bits/stdc++.h> using namespace std;  // Function to calculate the suffix array void suffixArray(string str, int N) {     // arr[] is array to count     // occurrence of each character     int arr[30] = { 0 };     for (int i = 0; i < N; i++) {         arr[str[i] - 'a']++;     }      // Finding prefix count of character     for (int i = 1; i < 30; i++) {         arr[i] = arr[i] + arr[i - 1];     }      int start[30];     start[0] = 0;     for (int i = 0; i < 29; i++) {         start[i + 1] = arr[i];     }      int ans[N] = { 0 };      // Iterating string in reverse order     for (int i = N - 1; i >= 0; i--) {          // Storing suffix array in ans[]         ans[start[str[i] - 'a']] = i;     }      for (int i = 0; i < N; i++)         cout << ans[i] << " "; }  // Driver code int main() {     string str = "prince";     int N = str.length();      suffixArray(str, N);     return 0; } 
Java
// Java program for the above approach import java.io.*; import java.lang.*; import java.util.*;  class GFG {     // Function to calculate the suffix array   static void suffixArray(String str, int N)   {      // arr[] is array to count     // occurrence of each character     int arr[] = new int[30];     for (int i = 0; i < N; i++) {       arr[str.charAt(i) - 'a']++;     }      // Finding prefix count of character     for (int i = 1; i < 30; i++) {       arr[i] = arr[i] + arr[i - 1];     }      int start[] = new int[30];     start[0] = 0;     for (int i = 0; i < 29; i++) {       start[i + 1] = arr[i];     }      int ans[]  = new int[N];      // Iterating string in reverse order     for (int i = N - 1; i >= 0; i--) {        // Storing suffix array in ans[]       ans[start[str.charAt(i) - 'a']] = i;     }      for (int i = 0; i < N; i++)       System.out.print(ans[i] + " ");   }    // Driver code   public static void main (String[] args)   {     String str = "prince";     int N = str.length();      suffixArray(str, N);   } }  // This code is contributed by hrithikgarg03188 
Python3
# Python code for the above approach  # Function to calculate the suffix array def suffixArray(str, N):        # arr[] is array to count     # occurrence of each character     arr = [0] * 30     for i in range(N):         arr[ord(str[i]) - ord('a')] += 1      # Finding prefix count of character     for i in range(1, 30):         arr[i] = arr[i] + arr[i - 1]      start = [0] * 30     start[0] = 0     for i in range(29):         start[i + 1] = arr[i]      ans = [0] * N      # Iterating string in reverse order     for i in range(N - 1, 0, -1):          # Storing suffix array in ans[]         ans[start[ord(str[i]) - ord('a')]] = i      for i in range(N):         print(ans[i], end=" ")  # Driver code str = "prince" N = len(str)  suffixArray(str, N)  # This code is contributed by gfgking 
C#
// C# code to implement above approach using System; class GFG {        // Function to calculate the suffix array     static void suffixArray(string str, int N)     {         // arr[] is array to count         // occurrence of each character         int[] arr = new int[30];         for (int i = 0; i < N; i++) {             arr[str[i] - 'a']++;         }          // Finding prefix count of character         for (int i = 1; i < 30; i++) {             arr[i] = arr[i] + arr[i - 1];         }          int[] start = new int[30];         start[0] = 0;         for (int i = 0; i < 29; i++) {             start[i + 1] = arr[i];         }          int[] ans = new int[N];          // Iterating string in reverse order         for (int i = N - 1; i >= 0; i--) {              // Storing suffix array in ans[]             ans[start[str[i] - 'a']] = i;         }          for (int i = 0; i < N; i++) {             Console.Write(ans[i]);             Console.Write(" ");         }     }      // Driver code     public static int Main()     {         string str = "prince";         int N = str.Length;          suffixArray(str, N);         return 0;     } }  // This code is contributed by Taranpreet 
JavaScript
   <script>         // JavaScript code for the above approach            // Function to calculate the suffix array         function suffixArray(str, N) {             // arr[] is array to count             // occurrence of each character             let arr = new Array(30).fill(0);             for (let i = 0; i < N; i++) {                 arr[str[i].charCodeAt(0) - 'a'.charCodeAt(0)]++;             }              // Finding prefix count of character             for (let i = 1; i < 30; i++) {                 arr[i] = arr[i] + arr[i - 1];             }              let start = new Array(30)             start[0] = 0;             for (let i = 0; i < 29; i++) {                 start[i + 1] = arr[i];             }              let ans = new Array(N).fill(0)              // Iterating string in reverse order             for (let i = N - 1; i >= 0; i--) {                  // Storing suffix array in ans[]                 ans[start[str[i].charCodeAt(0) - 'a'.charCodeAt(0)]] = i;             }              for (let i = 0; i < N; i++)                 document.write(ans[i] + " ")         }          // Driver code          let str = "prince";         let N = str.length;          suffixArray(str, N);            // This code is contributed by Potta Lokesh     </script> 

 
 


Output
4 5 2 3 0 1 


 

Time Complexity: O(N)
Auxiliary Space: O(N)


 


Next Article
Count of all unique substrings with non-repeating characters

P

prince_patel27
Improve
Article Tags :
  • Strings
  • Algo Geek
  • DSA
  • Algo-Geek 2021
  • Suffix-Array
Practice Tags :
  • Strings

Similar Reads

  • First non-repeating character of given string
    Given a string s of lowercase English letters, the task is to find the first non-repeating character. If there is no such character, return '$'. Examples: Input: s = "geeksforgeeks"Output: 'f'Explanation: 'f' is the first character in the string which does not repeat. Input: s = "racecar"Output: 'e'
    9 min read
  • Queries to find the last non-repeating character in the sub-string of a given string
    Given a string str, the task is to answer Q queries where every query consists of two integers L and R and we have to find the last non-repeating character in the sub-string str[L...R]. If there is no non-repeating character then print -1.Examples: Input: str = "GeeksForGeeks", q[] = {{2, 9}, {2, 3}
    11 min read
  • Find the last non repeating character in string
    Given a string str, the task is to find the last non-repeating character in it. For example, if the input string is "GeeksForGeeks", then the output should be 'r' and if the input string is "GeeksQuiz" then the output should be 'z'. if there is no non-repeating character then print -1.Examples: Inpu
    5 min read
  • Find frequency of each character with positions in given Array of Strings
    Given an array, arr[] consisting of N strings where each character of the string is lower case English alphabet, the task is to store and print the occurrence of every distinct character in every string. Examples:  Input: arr[] = { "geeksforgeeks", "gfg" }Output: Occurrences of: e = [1 2] [1 3] [1 1
    7 min read
  • Count of all unique substrings with non-repeating characters
    Given a string str consisting of lowercase characters, the task is to find the total number of unique substrings with non-repeating characters. Examples: Input: str = "abba" Output: 4 Explanation: There are 4 unique substrings. They are: "a", "ab", "b", "ba". Input: str = "acbacbacaa" Output: 10 App
    6 min read
  • Print the frequency of adjacent repeating characters in given string
    Given a string str of length N. The task is to print the frequency of adjacent repeating characters. Examples: Input: str = "Hello"Output: l: 2Explanation: Consecutive Repeating Character from the given string is "l" and its frequency is 2. Input: str = "Hellolllee"Output: l: 2 l: 3 e: 2Explanation:
    5 min read
  • Find the Nth occurrence of a character in the given String
    Given string str, a character ch, and a value N, the task is to find the index of the Nth occurrence of the given character in the given string. Print -1 if no such occurrence exists. Examples: Input: str = "Geeks", ch = 'e', N = 2 Output: 2 Input: str = "GFG", ch = 'e', N = 2 Output: -1 Recommended
    7 min read
  • Find Strings formed by replacing prefixes of given String with given characters
    Given a String ( S ) of length N and with that String, we need to print a triangle out of it. The triangle should start with the given string and keeps shrinking downwards by removing one character from the beginning of the string. The spaces on the left side of the triangle should be replaced with
    9 min read
  • Subsequences of given string consisting of non-repeating characters
    Given a string str of length N, the task is to print all possible distinct subsequences of the string str which consists of non-repeating characters only. Examples: Input: str = "abac" Output: a ab abc ac b ba bac bc c Explanation: All possible distinct subsequences of the strings are { a, aa, aac,
    7 min read
  • Count of strings that does not contain any character of a given string
    Given an array arr containing N strings and a string str, the task is to find the number of strings that do not contain any character of string str. Examples: Input: arr[] = {"abcd", "hijk", "xyz", "ayt"}, str="apple"Output: 2Explanation: "hijk" and "xyz" are the strings that do not contain any char
    8 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences