VOOZH about

URL: https://www.geeksforgeeks.org/dsa/consecutive-sequenced-numbers-in-a-string/

⇱ Consecutive sequenced numbers in a string - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Consecutive sequenced numbers in a string

Last Updated : 24 Apr, 2025

Given a string s that contains only numeric digits, we need to check whether that strings contains numbers in a consecutive sequential manner in increasing order. If the string contains a valid sequence of consecutive integers, print "Yes" followed by the starting number of the sequence. Otherwise, print "No".

Note: Negative numbers are not considered part of this problem. So we consider that input only contains non negative integer.

Examples: 

Input : s = "1234"
Output : "Yes", "1"
Explanation : There are 1, 2, 3, 4 which are consecutive and in increasing order and the starting number is 1

Input : s = "91012"
Output : "No"
Explanation : There are no such sequence in the string.

Input : s = "99100"
Output : "Yes", "99"
Explanation : The consecutive sequential
numbers are 99, 100

Input : s = "010203"
Output : "No"
Explanation : Although at first glance there seems to be 01, 02, 03. But those wouldn't be considered a number. 01 is not 1 it's 0, 1

The idea is to try all lengths starting from one. We start taking length 1 or one character at first (assuming that our string starts with 1 digit number) and then form a new string by concatenating the next number until the length of new string is equal to original string.  If length 1 does not give us result, then we try length 2 and so on until, either we get the desired sequence or we have tried till string-ength/2

Let's take string "99100"

👁 Image


Output
Yes, 99

Time Complexity: O(n2), n is the size of the given string.
Auxiliary Space: O(n)

Comment
Article Tags: