Check if an Array Contains a Value
Solve this ProblemEasy5 min
Topics
BasicsArraysSearching
Companies
TCSInfosysWipro
Given an array
nums and a target, return true if the target appears anywhere in the array and false otherwise.
This yes/no question is the simplest kind of search. The key idea is the early exitEarly ExitLeaving a loop (or function) as soon as the answer is known, instead of finishing all iterations.: as soon as a match appears, the answer is certain, but "not found" can only be decided after every element has been checked.
Test Case 1:
Input:nums = [6, 2, 9, 4], target = 9
Output:true
Explanation:9 is in the array.
Test Case 2:
Input:nums = [6, 2, 9, 4], target = 5
Output:false
Explanation:5 is not.
Constraints
- ◆
1 ≤ nums.length ≤ 1000 - ◆
-1000000 ≤ nums[i], target ≤ 1000000
Try the Dry Run
Approach & Solutions
Scan with Early ExitGood
Look at each element in turn. The moment one equals the target, return true — there is no need to look further. If the loop finishes without a match, the value is not there, so return false.
Time
O(n)Space
O(1)Java
class Solution {
public boolean containsValue(int[] nums, int target) {
for (int value : nums) {
if (value == target) {
return true;
}
}
return false;
}
}Built-in Membership TestOptimal
Use the language's ready-made check: anyMatch in Java, the in operator in Python, std::find in C++ and includes in JavaScript. Each performs the same scan internally. C has no built-in, so it keeps the loop.
Time
O(n)Space
O(1)Java
class Solution {
public boolean containsValue(int[] nums, int target) {
return Arrays.stream(nums).anyMatch(value -> value == target);
}
}