Skip to main content
Back to problems
#3
Medium Algorithms

Longest substring without repating characters

Hash Table String Sliding Window
38.5% acceptance
Jan 12, 2026
44560
2185
Given a string s, find the length of the longest substring without duplicate characters.

Solution

Rust
Time O(n)
Space O(n)
LeetCode
solution.rs
use std::collections::HashMap;

impl Solution {
  pub fn length_of_longest_substring(s: String) -> i32 {
    let mut map: HashMap<char, usize> = HashMap::new();
    let mut max_len = 0;
    let mut start = 0;
  
    for (end, ch) in s.chars().enumerate() {
      // If character exists and is within current window
      if let Some(&last_pos) = map.get(&ch) {
        if last_pos >= start {
          start = last_pos + 1;
        }
      }
      map.insert(ch, end);
      max_len = max_len.max(end - start + 1);
    }
  
    max_len as i32
  }
}