Approaches

💡

Intuition

Time O(n²)Space O(1)

The brute-force approach involves generating all possible substrings of the input string and checking for duplicates. This method is straightforward but inefficient for larger strings.

⚙️

Algorithm

3 steps
  1. 1Step 1: Generate all possible substrings of the string.
  2. 2Step 2: Store each substring in a set and check if it already exists in the set.
  3. 3Step 3: Keep track of the longest substring found that has duplicates.
solution.py13 lines
1# Full working Python code
2
3def longest_duplicate_substring(s):
4    n = len(s)
5    longest = ""
6    for i in range(n):
7        for j in range(i + 1, n + 1):
8            substring = s[i:j]
9            if s.count(substring) > 1 and len(substring) > len(longest):
10                longest = substring
11    return longest
12
13print(longest_duplicate_substring("banana"))  # Output: "ana"

Complexity note: The time complexity is O(n²) because we generate all substrings in a nested loop, and checking for duplicates takes linear time. The space complexity is O(1) as we are not using any additional data structures that grow with input size.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.