AlgoMaster Logo

Longest Duplicate Substring

Ashish

Ashish Pratap Singh

hard

Problem Description

Solve it on LeetCode

Approaches

1. Brute Force Approach

Intuition:

The brute force approach is to generate all possible substrings and check if more than one instance of a substring exists. Although this will work eventually, it's far from optimal. Given the nature of substrings, we can sort them and then check adjacent pairs for duplicates.

The general idea is to consider substrings of all possible lengths, starting from the longest. If we find a duplicate substring of a certain length, we record that as our longest duplicate substring.

Code:

2. Optimized Approach using Binary Search and Rolling Hash

Intuition:

The optimized approach uses binary search combined with a rolling hash technique to efficiently determine the longest duplicate substring.

  1. Binary Search: We perform a binary search on the length of the substring. Initially, set left as 1 and right as n (length of string).
  2. Rolling Hash: Pre-calculate the hash values for substrings to avoid recalculating hash values for overlapping sequences. This can be efficiently achieved using powers of a base number and modulus operations.

This method narrows down to the longest possible duplicate substring by leveraging the logarithmic exploration of the binary search and the efficiency of rolling hash.

Code: