Length of the longest substring with no consecutive same letters
Last Updated :
23 Mar, 2023
Given a string str, the task is to find the length of the longest sub-string which does not have any pair of consecutive same characters.
Examples:
Input: str = "abcdde"
Output: 4
"abcd" is the longest
Input: str = "ccccdeededff"
Output: 5
"ededf" is the longest
Approach: The following steps can be followed to solve the above problem:
- Initialize cnt and maxi as 1 initially, since this is the minimum answer of the length of the longest answer.
- Iterate in the string from 1 to n - 1 and increment cnt by 1 if str[i] != str[i - 1].
- If str[i] == str[i - 1], then re-initialize cnt as 1 and maxi to max(maxi, cnt).
Below is the implementation of the above approach:
C++
// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
// Function to return the length
// of the required sub-string
int longestSubstring(string s)
{
int cnt = 1;
int maxi = 1;
// Get the length of the string
int n = s.length();
// Iterate in the string
for (int i = 1; i < n; i++) {
// Check for not consecutive
if (s[i] != s[i - 1])
cnt++;
else {
// If cnt greater than maxi
maxi = max(cnt, maxi);
// Re-initialize
cnt = 1;
}
}
// Check after iteration
// is complete
maxi = max(cnt, maxi);
return maxi;
}
// Driver code
int main()
{
string s = "abcdde";
cout << longestSubstring(s);
return 0;
}
Java
// Java implementation of the approach
import java.lang.Math;
class GfG
{
// Function to return the length
// of the required sub-string
static int longestSubstring(String s)
{
int cnt = 1, maxi = 1;
// Get the length of the string
int n = s.length();
// Iterate in the string
for (int i = 1; i < n; i++)
{
// Check for not consecutive
if (s.charAt(i) != s.charAt(i-1))
cnt++;
else
{
// If cnt greater than maxi
maxi = Math.max(cnt, maxi);
// Re-initialize
cnt = 1;
}
}
// Check after iteration is complete
maxi = Math.max(cnt, maxi);
return maxi;
}
// Driver code
public static void main(String []args)
{
String s = "abcdde";
System.out.println(longestSubstring(s));
}
}
// This code is contributed by Rituraj Jain
C#
// C# implementation of the approach
using System;
class GfG
{
// Function to return the length
// of the required sub-string
static int longestSubstring(string s)
{
int cnt = 1, maxi = 1;
// Get the length of the string
int n = s.Length;
// Iterate in the string
for (int i = 1; i < n; i++)
{
// Check for not consecutive
if (s[i] != s[i - 1])
cnt++;
else
{
// If cnt greater than maxi
maxi = Math.Max(cnt, maxi);
// Re-initialize
cnt = 1;
}
}
// Check after iteration is complete
maxi = Math.Max(cnt, maxi);
return maxi;
}
// Driver code
static void Main()
{
string s = "abcdde";
Console.WriteLine(longestSubstring(s));
}
}
// This code is contributed by mits
Python3
# Python3 implementation of the approach
# Function to return the length
# of the required sub-string
def longestSubstring(s) :
cnt = 1;
maxi = 1;
# Get the length of the string
n = len(s);
# Iterate in the string
for i in range(1, n) :
# Check for not consecutive
if (s[i] != s[i - 1]) :
cnt += 1;
else :
# If cnt greater than maxi
maxi = max(cnt, maxi);
# Re-initialize
cnt = 1;
# Check after iteration
# is complete
maxi = max(cnt, maxi);
return maxi;
# Driver code
if __name__ == "__main__" :
s = "abcdde";
print(longestSubstring(s));
# This code is contributed by Ryuga
PHP
<?php
// PHP implementation of the approach
// Function to return the length
// of the required sub-string
function longestSubstring($s)
{
$cnt = 1;
$maxi = 1;
// Get the length of the string
$n = strlen($s);
// Iterate in the string
for ($i = 1; $i < $n; $i++)
{
// Check for not consecutive
if ($s[$i] != $s[$i - 1])
$cnt++;
else
{
// If cnt greater than maxi
$maxi = max($cnt, $maxi);
// Re-initialize
$cnt = 1;
}
}
// Check after iteration
// is complete
$maxi = max($cnt, $maxi);
return $maxi;
}
// Driver code
$s = "abcdde";
echo longestSubstring($s);
// This code is contributed by Akanksha Rai
?>
JavaScript
<script>
// javascript implementation of the approach class GfG
// Function to return the length
// of the required sub-string
function longestSubstring(s)
{
var cnt = 1, maxi = 1;
// Get the length of the string
var n = s.length;
// Iterate in the string
for (i = 1; i < n; i++)
{
// Check for not consecutive
if (s.charAt(i) != s.charAt(i-1))
cnt++;
else
{
// If cnt greater than maxi
maxi = Math.max(cnt, maxi);
// Re-initialize
cnt = 1;
}
}
// Check after iteration is complete
maxi = Math.max(cnt, maxi);
return maxi;
}
// Driver code
var s = "abcdde";
document.write(longestSubstring(s));
// This code contributed by shikhasingrajput
</script>
Time Complexity: O(n)
Auxiliary Space: O(1)
Approach 2: Using HashTable:
- Create a hash table to keep track of the most recent occurrence of each character.
- Initialize two pointers, left and right, to the beginning of the string.
- Iterate through the string with the right pointer, updating the hash table and the length of the current substring with each new character encountered.
- If a repeated character is encountered, move the left pointer to the next character after the previously occurring instance of that character and update the hash table and substring length accordingly.
- Keep track of the maximum substring length encountered so far.
- Return the maximum substring length.
Here's the implementation of this approach in C++:
C++
#include <bits/stdc++.h>
using namespace std;
int longestSubstring(string s) {
unordered_map<char, int> mp;
int left = 0, right = 0, maxLen = 0;
while (right < s.length()) {
char c = s[right];
if (mp.find(c) != mp.end() && mp[c] >= left) {
left = mp[c] + 1;
}
mp[c] = right;
maxLen = max(maxLen, right - left + 1);
right++;
}
return maxLen;
}
int main() {
string s = "abcdde";
cout << longestSubstring(s) << endl;
return 0;
}
Java
import java.util.*;
public class Main {
public static int longestSubstring(String s) {
Map<Character, Integer> mp = new HashMap<>();
int left = 0, right = 0, maxLen = 0;
while (right < s.length()) {
char c = s.charAt(right);
if (mp.containsKey(c) && mp.get(c) >= left) {
left = mp.get(c) + 1;
}
mp.put(c, right);
maxLen = Math.max(maxLen, right - left + 1);
right++;
}
return maxLen;
}
public static void main(String[] args) {
String s = "abcdde";
System.out.println(longestSubstring(s));
}
}
Python3
def longestSubstring(s):
mp = {}
left = 0
maxLen = 0
for right in range(len(s)):
if s[right] in mp and mp[s[right]] >= left:
left = mp[s[right]] + 1
mp[s[right]] = right
maxLen = max(maxLen, right - left + 1)
return maxLen
if __name__ == "__main__":
s = "abcdde"
maxLen = longestSubstring(s)
print(maxLen)
C#
// Added C# code for the above approach
using System;
using System.Collections.Generic;
class Program {
static int LongestSubstring(string s)
{
Dictionary<char, int> mp
= new Dictionary<char, int>();
int left = 0, right = 0, maxLen = 0;
while (right < s.Length) {
char c = s[right];
if (mp.ContainsKey(c) && mp[c] >= left) {
left = mp[c] + 1;
}
mp[c] = right;
maxLen = Math.Max(maxLen, right - left + 1);
right++;
}
return maxLen;
}
static void Main(string[] args)
{
string s = "abcdde";
Console.WriteLine(LongestSubstring(s));
}
}
// Contributed by adityasha4x71
JavaScript
function longestSubstring(s) {
const mp = {};
let left = 0;
let maxLen = 0;
for (let right = 0; right < s.length; right++) {
if (s[right] in mp && mp[s[right]] >= left) {
left = mp[s[right]] + 1;
}
mp[s[right]] = right;
maxLen = Math.max(maxLen, right - left + 1);
}
return maxLen;
}
const s = "abcdde";
const maxLen = longestSubstring(s);
console.log(maxLen);
Time Complexity: O(n)
Auxiliary Space: O(min(m, n))
Similar Reads
DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Dijkstra's Algorithm to find Shortest Paths from a Source to all Given a weighted undirected graph represented as an edge list and a source vertex src, find the shortest path distances from the source vertex to all other vertices in the graph. The graph contains V vertices, numbered from 0 to V - 1.Note: The given graph does not contain any negative edge. Example
12 min read
Selection Sort Selection Sort is a comparison-based sorting algorithm. It sorts an array by repeatedly selecting the smallest (or largest) element from the unsorted portion and swapping it with the first unsorted element. This process continues until the entire array is sorted.First we find the smallest element an
8 min read