LeetCode Find First and Last Position of Element in Sorted Array (JavaScript), 이분 탐색

2025. 11. 24. 19:55·코딩테스트/LeetCode

링크 : https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/

문제 설명

더보기

Given an array of integers nums sorted in non-decreasing order, find the starting and ending position of a given target value.

If target is not found in the array, return [-1, -1].

You must write an algorithm with O(log n) runtime complexity.

Example 1:

Input: nums = [5,7,7,8,8,10], target = 8
Output: [3,4]

Example 2:

Input: nums = [5,7,7,8,8,10], target = 6
Output: [-1,-1]

Example 3:

Input: nums = [], target = 0
Output: [-1,-1]

Constraints:

  • 0 <= nums.length <= 105
  • 109 <= nums[i] <= 109
  • nums is a non-decreasing array.
  • 109 <= target <= 109

문제 풀이

이분 탐색(Binary search) 알고리즘을 이용하여 O(logN)으로 해결

target의 가장 작은 index, 가장 큰 index를 찾기 위해 기존 이분 탐색에서 추가된 부분

-> nums[mid] === target인 경우 반복문을 멈추는게 아닌 더 작은 값, 더 큰 값을 찾기 위해 left, right를 조정

  • 가장 작은 인덱스(startIndex) 구하기
    • nums[mid] === target이라면 더 작은 값을 구하기 위해 right를 mid - 1로 조정 -> 현재 기준(mid)에서 좌측 구간을 탐색하기 위해
  • 가장 큰 인덱스(endIndex) 구하기
    • nums[mid] === target이라면 더 큰 값을 구하기 위해 left를 mid + 1로 조정 -> 현재 기준(mid)에서 우측 구간을 탐색하기 위해
/**
 * @param {number[]} nums
 * @param {number} target
 * @return {number[]}
 */
var searchRange = function(nums, target) {
    const find_index = (nums, target, isStart) => {
        let left = 0;
        let right = nums.length - 1;
        let findIndex = -1;

        while (left <= right) {
            const mid = Math.floor((left + right) / 2);

            if (nums[mid] === target) {
                findIndex = mid;

                if (isStart) {
                    right = mid - 1;
                } else {
                    left = mid + 1;
                }
            } else if (nums[mid] < target) {
                left = mid + 1;
            } else { // nums[mid] > target
                right = mid - 1;
            }
        }

        return findIndex;
    }

    const startIndex = find_index(nums, target, true);
    const endIndex = find_index(nums, target, false);

    return [startIndex, endIndex];
};

결론

이분 탐색(Binary Search) 알고리즘을 이용하여 문제를 해결

문제의 핵심은 target과 같은 값을 발견했을 때 반복을 멈추는게 아닌 더 작거나 큰 값을 찾기 위해 left, right 값을 조정하는 로직을 작성하는 것

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

LeetCode Count and Say (JavaScript)  (0) 2025.11.25
LeetCode Valid Sudoku (JavaScript), Set  (0) 2025.11.24
LeetCode Next Permutaion (JavaScript), 순열  (0) 2025.11.22
LeetCode Divide Two Integers (JavaScript), 비트 연산  (0) 2025.11.21
LeetCode Swap Nodes in Pairs (JavaScript)  (0) 2025.11.19
'코딩테스트/LeetCode' 카테고리의 다른 글
  • LeetCode Count and Say (JavaScript)
  • LeetCode Valid Sudoku (JavaScript), Set
  • LeetCode Next Permutaion (JavaScript), 순열
  • LeetCode Divide Two Integers (JavaScript), 비트 연산
의현
의현
개발하는 하루
  • 의현
    UIHYEON
    의현
  • 링크

    • 김의현 포트폴리오
    • GitHub
    • LinkedIn
  • 전체
    오늘
    어제
    • 분류 전체보기 (213) N
      • 프론트엔드 (64) N
        • JavaScript (51)
        • HTML (3)
        • React (7) N
        • CSS (2)
        • CS (1)
      • 프로젝트 (19)
        • Portfolio 사이트 개발 (19)
      • 코딩테스트 (127) N
        • 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)
        • 프로그래머스 (61)
        • LeetCode (38) N
  • 인기 글

  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
의현
LeetCode Find First and Last Position of Element in Sorted Array (JavaScript), 이분 탐색
상단으로

티스토리툴바