Problem 34

Abstract / Summary

Given a sorted array and a target value, find the starting and ending positions where the target appears.

Note

The full problem description, including helpful examples, can be found on LeetCode.

C++ 0034.cpp

class Solution {
public:
    vector<int> searchRange(vector<int>& nums, int target) {
        auto one = lower_bound(nums.begin(), nums.end(), target);
        auto two = lower_bound(one,          nums.end(), target + 1);

        if (one == nums.end() || *one != target)
            return { -1, -1 };

        return { int(one - nums.begin()), int(two - nums.begin()) - 1 };
    }
};
12 lines | 398 bytes | submitted August 7, 2023 | GitHub   tab size 4

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 49% (7+ million submissions).

Typical patterns to solve this problem:
  • Array
  • Binary Search
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The presented Solution class implements a method searchRange that receives a sorted integer vector nums and an integer target. Its purpose is to locate the first and last indices where target appears in the vector. If the target does not exist, the method returns {-1, -1}. The implementation relies on the standard library function lower_bound to perform binary searches, thereby achieving an efficient solution for the problem.

Key Steps

The algorithm proceeds in three distinct stages.

The first stage identifies the leftmost occurrence of target by invoking lower_bound on the entire range of the vector.

auto one = lower_bound(nums.begin(), nums.end(), target);

The second stage finds the position just past the rightmost occurrence of target. It starts the search from the iterator returned by the first stage, which narrows the search space and avoids re-examining elements that are already known to be less than target.

auto two = lower_bound(one, nums.end(), target + 1);

The third stage validates whether the target was actually found. If the iterator one points to the end of the vector or the dereferenced value does not equal target, the method returns the sentinel pair {-1, -1}. Otherwise, it computes the integer indices by subtracting the beginning iterator from one and two, adjusting the right index by subtracting one to obtain the last valid position.

if (one == nums.end() || *one != target)
    return { -1, -1 };

return { int(one - nums.begin()), int(two - nums.begin()) - 1 };

Edge Cases Handled

When the input vector is empty, lower_bound immediately yields nums.end(). The subsequent check one == nums.end() triggers the early return of {-1, -1}, correctly indicating the absence of any target.

If the target value is smaller than all elements in the vector, the first lower_bound call returns an iterator to the first element, but the condition *one != target fails, leading again to the sentinel result.

When the target is larger than every element, lower_bound returns nums.end(). The same early-return condition captures this scenario.

For vectors that contain multiple consecutive occurrences of the target, the first lower_bound finds the first occurrence, while the second lower_bound-searching for target + 1-lands on the element immediately after the last occurrence. Subtracting one from that position yields the correct index of the final target element.

If the target appears exactly once, both one and two will point to the same element and the element after it, respectively, resulting in a range where the start and end indices are identical, which the method returns accurately.

Performance Optimizations

The implementation leverages the logarithmic search behavior of lower_bound, which performs a binary search on the sorted range. By calling lower_bound twice, the algorithm maintains an overall logarithmic time profile while avoiding a full linear scan.

Starting the second lower_bound from the iterator one rather than from nums.begin() reduces the number of comparisons needed to locate the upper bound, because all elements before one are already known to be less than target.

The use of iterator arithmetic (one - nums.begin()) provides constant-time index calculation without additional loops or auxiliary data structures. Casting the result to int ensures the return type matches the expected vector of integers.

Overall, the code achieves a compact and efficient solution by combining standard library facilities with careful iterator management, resulting in minimal overhead and clear expression of the intended algorithmic steps.

written by openai gpt

ELI5 - Simplified Explanation

Imagine you have a long row of numbered toy blocks lined up from smallest to biggest. You are looking for all the blocks that have a specific number written on them. Since the blocks are already sorted, you do not have to pick up every single one to check.

The code works like a smart scout who starts at the beginning of the row. The first part, called lower bound, sends the scout to find the very first block that matches the number you want. Once the scout finds that spot, it remembers exactly where it is.

Then, the code sends the scout back out again to find the spot where the numbers would change into something bigger than your target. This helps the scout see where the group of your matching blocks ends.

If the scout realizes that the first spot is actually at the very end of the row, or if the number there is not the one you were looking for at all, it knows those blocks are missing. Otherwise, it uses the starting spot and the ending spot to tell you the sandwich of blocks that hold your favorite number.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 29 | median = 9 | μ = 8.66 | σ = 0.66

Complexity Analysis

not analyzed yet

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca C++ Python Java C# Rust JS Go PHP TS
LeetcodeHelp C++ Python Java
MemoryLimitExceeded C++ Python
Progiez C++ Python Java
github aylei Rust
begeekmyfriend C
BigEggStudy C#
black-shadows C++
chandansgowda Python
charles-wangkai Java
DimitrisJim Go
everthis JS
fartem Ruby
FelixFan1122 C#
fengvyi C++
fpdjsns C++
gaosq0604 Python
Garvit244 Python
halfrost Go
JoshCrozier JS
keineahnung2345 C++
Krazune C++
lennylxx C++
linouk23 C++
lkwq007 Python
luangong C++
MacJim C++
qiyuangong Java
ruoru Rust
shreymehul C#
sonugiri1043 C++
suxrobGM C#
trung-hn Python
varunu28 Java
vli02 C
vthwang Java
wisdompeak C++
XiaotaoGuo C++
YuriSpiridonov Python
zfang399 C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, C#, Go, Java, JavaScript, PHP, Python, Rust, TypeScript
LeetcodeHelp C++, Java, Python
MemoryLimitExceeded Python, C++
Progiez C++, Java, Python
aylei Rust
begeekmyfriend C
BigEggStudy C#
black-shadows C++, C++
chandansgowda Python
charles-wangkai Java
DimitrisJim Go
everthis JavaScript
fartem Ruby
FelixFan1122 C#
fengvyi C++
fpdjsns C++
gaosq0604 Python
Garvit244 Python
halfrost Go
JoshCrozier JavaScript
keineahnung2345 C++
Krazune C++
lennylxx C++
linouk23 C++
lkwq007 Python
luangong C++
MacJim C++
qiyuangong Java
ruoru Rust
shreymehul C#
sonugiri1043 C++
suxrobGM C#
trung-hn Python
varunu28 Java
vli02 C
vthwang Java
wisdompeak C++
XiaotaoGuo C++
YuriSpiridonov Python
zfang399 C++
60 links | 42 authors | 11 languages

Videos

These are a few popular YouTube videos for this problem:
YouTube video 'First and Last Position of Element Sorted Array (LeetCode 34) | Full Solution | Study Algorithms'
Nikhil Lohia 16 mins
First and Last Position of Element Sorted Array (LeetCode 34) | Full Solution | Study Algorithms
YouTube video 'Find First and Last Position of Element in Sorted Array Leetcode 34 Solution | Searching and Sorting'
Pepcoding 9 mins
Find First and Last Position of Element in Sorted Array Leetcode 34 Solution | Searching and Sorting
YouTube video 'Find First and Last Position of Element in Sorted Array | Leetcode 34'
Ayushi Sharma 20 mins
Find First and Last Position of Element in Sorted Array | Leetcode 34
YouTube video '[Java] Leetcode 34. Find First and Last Position of Element in Sorted Array [Binary Search #6]'
Eric Programming 14 mins
[Java] Leetcode 34. Find First and Last Position of Element in Sorted Array [Binary Search #6]
YouTube video 'Find First and Last Position of Element in Sorted Array - LeetCode 34 - Binary Search'
One Code Man 9 mins
Find First and Last Position of Element in Sorted Array - LeetCode 34 - Binary Search
YouTube video '34 Find First and Last Position of Element in Sorted Array | Zero to FAANG | Searching in Arrays'
Programmers Zone 26 mins
34 Find First and Last Position of Element in Sorted Array | Zero to FAANG | Searching in Arrays
YouTube video 'Find First And Last Position Of Element In Sorted Array - LeetCode 34 - JavaScript'
AlgoJS 6 mins
Find First And Last Position Of Element In Sorted Array - LeetCode 34 - JavaScript
YouTube video 'Find First and Last Position of Element in Sorted Array #leetcode'
Deepti Talesra 13 mins
Find First and Last Position of Element in Sorted Array #leetcode
YouTube video 'Find First and Last Position of Element in Sorted Array | LeetCode 34 | Binary Search | Google'
Naresh Gupta 13 mins
Find First and Last Position of Element in Sorted Array | LeetCode 34 | Binary Search | Google
YouTube video 'Chinese - LeetCode 34. Find First and Last Position of Element in Sorted Array'
happygirlzt 11 mins
Chinese - LeetCode 34. Find First and Last Position of Element in Sorted Array
YouTube video 'Leetcode 34  Find First and Last Position of Element in Sorted Array | Binary Search Decoded'
Coding Decoded 12 mins
Leetcode 34 Find First and Last Position of Element in Sorted Array | Binary Search Decoded
YouTube video 'Find First and Last Position of Element in Sorted Array Python Solution - LeetCode #34'
Professor Oakes 7 mins
Find First and Last Position of Element in Sorted Array Python Solution - LeetCode #34
YouTube video 'Daily Leetcode #1287: Oct 09, 2023 - 34. Find First and Last Position of Element in Sorted Array'
Programming Live with Larry 7 mins
Daily Leetcode #1287: Oct 09, 2023 - 34. Find First and Last Position of Element in Sorted Array
YouTube video 'Find First and Last Position of Element in Sorted Array || Leetcode Daily Challenge'
CodeFreaks 8 mins
Find First and Last Position of Element in Sorted Array || Leetcode Daily Challenge
YouTube video 'LeetCode 34: Find First and Last Position of Element in Sorted Array | C# Solution | Binary Search |'
Code Scribbler 7 mins
LeetCode 34: Find First and Last Position of Element in Sorted Array | C# Solution | Binary Search |
YouTube video 'Daily Leetcode #846: Jul 25, 2022 - 34. Find First and Last Position of Element in Sorted Array'
Programming Live with Larry 5 mins
Daily Leetcode #846: Jul 25, 2022 - 34. Find First and Last Position of Element in Sorted Array
YouTube video '34. Find First and Last Position of Element in Sorted Array | Leetcode | Arrays | Fundamentals'
Coding with Tamilarasan 12 mins
34. Find First and Last Position of Element in Sorted Array | Leetcode | Arrays | Fundamentals
YouTube video '34. Find First and Last Position of Element in Sorted Array | LeetCode | Top 100 Liked'
Software Interviews Prep 19 mins
34. Find First and Last Position of Element in Sorted Array | LeetCode | Top 100 Liked
YouTube video '34. Find First and Last Position of Element in Sorted Array | October | C++ | Java | Python 3'
Mayur Programming Club 14 mins
34. Find First and Last Position of Element in Sorted Array | October | C++ | Java | Python 3
YouTube video 'LeetCode: 34. Find First and Last Position of Element in Sorted Array (Visualized)'
Code With Zi 18 mins
LeetCode: 34. Find First and Last Position of Element in Sorted Array (Visualized)
20 videos   did my crawler come up with invalid videos ? drop me a line.

Solved On The Same Day

40 easy 30 medium 1 hard
72 solutions   August 7, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality