Skip to content
Programming101
Programming101

Learn everything about programming

  • Home
  • CS Subjects
    • IoT – Internet of Things
    • Digital Communication
    • Human Values
  • Programming Tutorials
    • C Programming
    • Data structures and Algorithms
  • HackerRank Solutions
    • HackerRank Algorithms Solutions
    • HackerRank C problems solutions
    • HackerRank C++ problems solutions
    • HackerRank Java problems solutions
    • HackerRank Python problems solutions
Programming101
Programming101

Learn everything about programming

Leetcode Unique Substrings in Wraparound String problem solution

YASH PAL, 31 July 2024

In this Leetcode Unique Substrings in Wraparound String problem solution We define the string s to be the infinite wraparound string of “abcdefghijklmnopqrstuvwxyz”, so s will look like this:

“…zabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcd….”.

Given a string p, return the number of unique non-empty substrings of p are present in s.

Leetcode Unique Substrings in Wraparound String problem solution

Problem solution in Python.

def findSubstringInWraproundString(self, p: str) -> int:
        d={x:1 for x in p}
        cur=1
        for x in range(len(p)-1,-1,-1):
            if x==len(p)-1 or (ord(p[x+1])-ord(p[x]))%26!=1:
                cur=1
            else:
                cur+=1
                d[p[x]]=max(d[p[x]],cur)
        return sum(d.values())

Problem solution in Java.

class Solution {
    public int findSubstringInWraproundString(String p) {
        if(p.length()==0)return 0;
        int res=0;
        int table[]=new int[26];
        int dp[]=new int[p.length()];
        dp[0]=1;
        table[p.charAt(0)-'a']=1;
        for(int i=1;i<p.length();i++){
            char cur=p.charAt(i);
            char pre=p.charAt(i-1);
            if(cur-pre==1||(cur=='a'&&pre=='z')){
                dp[i]=dp[i-1]+1;
            }else{
                dp[i]=1;
            }
            table[cur-'a']=Math.max(table[cur-'a'],dp[i]);
        }
        for(int i : table)res+=i;
        return res;
    }
}

Problem solution in C++.

int findSubstringInWraproundString(string p) {
        int n=p.size(),ans=1,dp=1;
        vector<int> maxFound(26,0);
        maxFound[p[0]-'a']=1;
        for(int i=1;i<n;i++){
            if((p[i-1]-'a'+1)%26!=p[i]-'a'){
                dp=1;
            }else{
                dp++;
            }
            ans+=max(0,dp-maxFound[p[i]-'a']);
            maxFound[p[i]-'a']=max(maxFound[p[i]-'a'],dp);
        }
        return ans;
    }
coding problems

Post navigation

Previous post
Next post
  • HackerRank Separate the Numbers solution
  • How AI Is Revolutionizing Personalized Learning in Schools
  • GTA 5 is the Game of the Year for 2024 and 2025
  • Hackerrank Day 5 loops 30 days of code solution
  • Hackerrank Day 6 Lets Review 30 days of code solution
©2025 Programming101 | WordPress Theme by SuperbThemes