Check if array contains

Efficient way to check if array contains given value

How to check if array contains a given value ? This is an important interview question and frequently used operation during development. Below are the 5 ways to check that. Note the time complexity in the output for all the methods, you will understand simple for-each loop method is the efficient way compared to all.

Example: Check if array contains given value

Arrays.stream() Example

List Example

Set Example

Arrays.binarySearch() Example

Note: binarySearch() can only be used on sorted arrays to yield better results.

Using Simple for-each loop

Time Complexity

Below is the example code which includes all approaches and will help in measuring and analyzing the time required for this problem.

Output

Conclusion

Try increasing the size of array and see the time measured for each method, you will find clearly using a simple for-each loop method is more efficient than other methods.

Recommended Posts

Reference

Leave a Reply

avatar
  Subscribe  
Notify of