LeetCode Longest Substring Without Repeating Characters (JavaScript)

2026. 3. 19. 16:14·코딩테스트/LeetCode

링크 : https://leetcode.com/problems/longest-substring-without-repeating-characters/description/

문제 설명

더보기

Given a string s, find the length of the longest substring without duplicate characters.

Example 1:

Input: s = "abcabcbb"
Output: 3
Explanation: The answer is "abc", with the length of 3. Note that "bca" and "cab" are also correct answers.

Example 2:

Input: s = "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.

Example 3:

Input: s = "pwwkew"
Output: 3
Explanation: The answer is "wke", with the length of 3.
Notice that the answer must be a substring, "pwke" is a subsequence and not a substring.

Constraints:

  • 0 <= s.length <= 5 * 104
  • s consists of English letters, digits, symbols and spaces.

문제 풀이

접근 방식

  • 포인터를 2개 두어 해당 포인터의 길이 차이를 구하도록 함 (left, right)
  • 두 포인터 안에는 중복되는 문자가 존재하지 않아야 함 -> set 을 통해 관리
    • 특정 문자가 없어질 때까지 set 배열에서 제거 (while 문)
  • 현재 위치의 문자를 넣고 길이의 최댓값 계산 (right - left + 1)
/**
 * @param {string} s
 * @return {number}
 */
var lengthOfLongestSubstring = function(s) {
    let answer = 0;
    const str = new Set();
    let left = 0;

    for (let right = 0; right < s.length; right++) {
        while (str.has(s[right])) {
            str.delete(s[left]);
            left++;
        }

        str.add(s[right]);
        answer = Math.max(answer, right - left + 1);
    }

    return answer;
};

결론

O(n)의 시간복잡도로 해결.

중간에 문자열을 자르고 하는 메서드를 사용할 경우 길이가 길어짐에 따라 시간 초과 오류가 발생할 수 있음.

set을 통해 O(1)로 검색을 하도록 했고, for문을 한 번만 탐색해도 최대 길이를 구할 수 있도록 했음

 

* for문 안에 while문이 있으면 O(n^2)이 아닌가? 아니다.

for문 안에 while문으로 O(n^2)처럼 보일 수 있지만 실제 동작을 보면 다른걸 알 수 있다.

  • right 포인터 : 문자열을 처음부터 끝까지 한 번만 탐색 (n번)
  • left 포인터 : while 문 안에서 동작하지만, 전체 과정을 보면 문자열의 각 인덱스를 최대 한 번씩만 탐색함 (n번)
    • 즉, 한 번 left가 지나간 자리는 다시 돌아가지 않음 -> O(n^2)이 안되는 이유

따라서 모든 문자는 최대 두 번씩만 처리되기 때문에 연산 횟수는 2n에 비례해서 O(n)의 시간복잡도를 가지게 된다.

'코딩테스트 > LeetCode' 카테고리의 다른 글

LeetCode Edit Distance (JavaScript), DP  (0) 2026.03.26
LeetCode Unique Paths ll (JavaScript), DP  (0) 2026.03.24
LeetCode Median of Two Sorted Arrays (JavaScript), Binary Search, Two Pointer  (0) 2026.03.18
LeetCode Trapping Rain Water (JavaScript), Two pointer  (0) 2026.03.12
LeetCode Repeated DNA Sequences (JavaScript), Sliding window  (0) 2026.03.06
'코딩테스트/LeetCode' 카테고리의 다른 글
  • LeetCode Edit Distance (JavaScript), DP
  • LeetCode Unique Paths ll (JavaScript), DP
  • LeetCode Median of Two Sorted Arrays (JavaScript), Binary Search, Two Pointer
  • LeetCode Trapping Rain Water (JavaScript), Two pointer
의현
의현
개발하는 하루
  • 의현
    UIHYEON
    의현
  • 링크

    • 김의현 포트폴리오
    • GitHub
    • LinkedIn
  • 전체
    오늘
    어제
    • 분류 전체보기 (252)
      • AI (1)
      • Amazon Cloud (4)
        • EC2 (3)
        • Deploy (1)
      • 프론트엔드 (67)
        • JavaScript (52)
        • HTML (3)
        • React (9)
        • CSS (2)
        • CS (1)
      • 프로젝트 (21)
        • Portfolio 사이트 개발 (21)
      • 코딩테스트 (155)
        • Binary Search (2)
        • bfs (Breadth-first s.. (4)
        • dfs (Deapth-first se.. (1)
        • Greedy (1)
        • Dynamic Programming (1)
        • two pointer (4)
        • 구현 (2)
        • LIS(Longest Increasi.. (0)
        • 문자열 (3)
        • 자료구조 (6)
        • 비트마스크 (2)
        • 수학 (2)
        • 프로그래머스 (65)
        • LeetCode (62)
      • 자격증 (1)
  • 인기 글

  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
의현
LeetCode Longest Substring Without Repeating Characters (JavaScript)
상단으로

티스토리툴바