Problem 704

Abstract / Summary

Given a sorted list and a target value, determine if the target exists in the list.

Note

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

C++ 0704.cpp

class Solution {
public:
    int search(vector<int>& nums, int target) {
        auto i = lower_bound(nums.begin(), nums.end(), target);

        if (i == nums.end())
            return -1;

        if (*i == target)
            return i - nums.begin();

        return -1;
    }
};
14 lines | 297 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 61% (6+ 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 provided implementation defines a Solution class with a single public method search. The method receives a reference to a vector<int> named nums and an integer target. Its purpose is to locate the index of target within the sorted vector, returning -1 when the value is absent. The algorithm leverages the standard library function lower_bound to perform a binary search, thereby achieving logarithmic search time on a sorted range.

Key Steps

The first significant operation is the invocation of lower_bound:

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

lower_bound returns an iterator pointing to the first element that is not less than target. This iterator may point to the exact match, to a larger element, or to the end of the container if all elements are smaller than target.

The next step checks whether the iterator has reached the end of the vector:

if (i == nums.end())
    return -1;

If the iterator equals nums.end(), it indicates that every element in the vector is smaller than target, and consequently the target cannot be present.

When the iterator is not at the end, the code verifies that the dereferenced value matches the target:

if (*i == target)
    return i - nums.begin();

If the condition holds, the method computes the zero-based index by subtracting nums.begin() from the iterator, which yields the distance between the two iterators.

If the dereferenced value differs from target, the method concludes that the target is absent and returns -1:

return -1;

Edge Cases Handled

The algorithm gracefully handles an empty input vector. In that scenario, lower_bound immediately returns nums.end(), triggering the early exit that returns -1. This avoids any dereferencing of an invalid iterator.

When the target is smaller than the smallest element in the vector, lower_bound yields an iterator to the first element. The subsequent equality check fails, and the method returns -1, correctly indicating absence.

If the target is larger than the largest element, lower_bound returns nums.end(). The early end-of-range check captures this case, again returning -1.

When the target appears multiple times, lower_bound points to the first occurrence because it finds the first element not less than the target. The index calculation therefore returns the index of the earliest matching element, which aligns with typical expectations for a search routine.

Performance Optimizations

The core optimization stems from the use of lower_bound, a standard algorithm that implements binary search internally. By delegating the search to this library routine, the code benefits from a highly tuned implementation that minimizes branch mispredictions and leverages iterator arithmetic efficiently.

The method avoids any explicit loops or additional data structures, keeping the memory footprint minimal. The distance calculation i - nums.begin() is performed using iterator subtraction, which for random-access iterators (as provided by vector) is a constant-time operation.

Early termination is achieved through the if (i == nums.end()) guard. This prevents unnecessary dereferencing when the target lies beyond the range of the container, saving a potential comparison.

Overall, the combination of a standard binary search, constant-time index computation, and early exit conditions results in a concise and performant solution for locating an element in a sorted integer vector.

written by openai gpt

ELI5 - Simplified Explanation

Imagine you have a long line of numbered toy blocks all arranged in order from smallest to biggest. You want to find one specific block with a certain number written on it.

The code acts like a very fast helper who starts by looking at the middle of the line to guess where that block might be hiding. Because the blocks are already in order, the helper can quickly skip over big sections that are too small or too large, which saves a lot of time.

The first part of the code asks the helper to find the first spot where the target block could live. If the helper reaches the very end of the line and still has not found the target, it tells you that the block is missing. If the helper stops and sees that the block at that spot is exactly the one you were looking for, it tells you the position number of that block in the line so you can go pick it up. If the helper stops and the block is not the right number, it lets you know the block is not there.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 8 | μ = 7.67 | σ = 1.33

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++ Java Python TS
WalkCCC C++ Java Python
leetcode.ca C++ Java Rust C# Python JS Go TS
LeetcodeHelp C++ Java Python
Progiez C++ Java Python
github AdelDaniel Dart
aylei Rust
begeekmyfriend C
BigEggStudy C#
black-shadows C++
bujosa Rust
chandansgowda Python
charles-wangkai Java
Dijkstra-Edu C++
DimitrisJim C
everthis JS
fartem Ruby
fpdjsns C++
gouthampradhan Java
halfrost Go
JoshCrozier JS
keineahnung2345 C++
Krazune C++
lkwq007 Python
muhammadfarhankt Go
ruoru Rust
shreymehul C#
sonugiri1043 C++
suxrobGM C#
varunu28 Java
vthwang Java
yuanliu666 Java
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, C#, Go, Java, JavaScript, Python, Rust, TypeScript
LeetcodeHelp C++, Java, Python
Progiez C++, Java, Python
AdelDaniel Dart
aylei Rust
begeekmyfriend C
BigEggStudy C#
black-shadows C++, C++
bujosa Rust
chandansgowda Python
charles-wangkai Java
Dijkstra-Edu C++
DimitrisJim C
everthis JavaScript
fartem Ruby
fpdjsns C++
gouthampradhan Java
halfrost Go
JoshCrozier JavaScript
keineahnung2345 C++
Krazune C++
lkwq007 Python
muhammadfarhankt Go
ruoru Rust
shreymehul C#
sonugiri1043 C++
suxrobGM C#
varunu28 Java
vthwang Java
yuanliu666 Java
48 links | 32 authors | 11 languages

Videos

5 videos   did my crawler come up with invalid videos ? drop me a line.

Solved On The Same Day

39 easy 31 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