Binary TreesBinary Trees36

  1. 1Preorder Traversal of a Binary Tree using Recursion
  2. 2Preorder Traversal of a Binary Tree using Iteration
  3. 3Postorder Traversal of a Binary Tree Using Recursion
  4. 4Postorder Traversal of a Binary Tree using Iteration
  5. 5Level Order Traversal of a Binary Tree using Recursion
  6. 6Level Order Traversal of a Binary Tree using Iteration
  7. 7Reverse Level Order Traversal of a Binary Tree using Iteration
  8. 8Reverse Level Order Traversal of a Binary Tree using Recursion
  9. 9Find Height of a Binary Tree
  10. 10Find Diameter of a Binary Tree
  11. 11Find Mirror of a Binary Tree - Todo
  12. 12Inorder Traversal of a Binary Tree using Recursion
  13. 13Inorder Traversal of a Binary Tree using Iteration
  14. 14Left View of a Binary Tree
  15. 15Right View of a Binary Tree
  16. 16Top View of a Binary Tree
  17. 17Bottom View of a Binary Tree
  18. 18Zigzag Traversal of a Binary Tree
  19. 19Check if a Binary Tree is Balanced
  20. 20Diagonal Traversal of a Binary Tree
  21. 21Boundary Traversal of a Binary Tree
  22. 22Construct a Binary Tree from a String with Bracket Representation
  23. 23Convert a Binary Tree into a Doubly Linked List
  24. 24Convert a Binary Tree into a Sum Tree
  25. 25Find Minimum Swaps Required to Convert a Binary Tree into a BST
  26. 26Check if a Binary Tree is a Sum Tree
  27. 27Check if All Leaf Nodes are at the Same Level in a Binary Tree
  28. 28Lowest Common Ancestor (LCA) in a Binary Tree
  29. 29Solve the Tree Isomorphism Problem
  30. 30Check if a Binary Tree Contains Duplicate Subtrees of Size 2 or More
  31. 31Check if Two Binary Trees are Mirror Images
  32. 32Calculate the Sum of Nodes on the Longest Path from Root to Leaf in a Binary Tree
  33. 33Print All Paths in a Binary Tree with a Given Sum
  34. 34Find the Distance Between Two Nodes in a Binary Tree
  35. 35Find the kth Ancestor of a Node in a Binary Tree
  36. 36Find All Duplicate Subtrees in a Binary Tree

Linear Search in Array using Loop



Problem Statement

Given an array of integers and a target value called key, your task is to search for the key in the array using linear search.

This is the simplest and most intuitive way to search for a value in an array.

Examples

Input ArrayKeyOutputDescription
[10, 20, 30, 40, 50]30230 is present at index 2
[5, 8, 12, 8, 20]81First occurrence of 8 is at index 1
[1, 2, 3, 4, 5]6-16 is not in the array
[]5-1Array is empty, so nothing to search
[42]420Single element matches the key
[42]99-1Single element does not match
[1, 1, 1, 1]10All elements match, but return the first index

Solution

Linear search is one of the most basic and widely used methods for finding a value in an array. The idea is simple: go through each element from the beginning and compare it with the target value (key).

How It Works in Practice

Start from the first element of the array and compare it with the key:

  • If the current element equals the key, we immediately return that index.
  • If not, move to the next element and repeat.

If we reach the end of the array without finding the key, we return -1 to indicate that the key is not present.

Understanding Different Scenarios

  • Normal Case: If the key exists somewhere in the array, linear search will find it. The time it takes depends on where the key is located—beginning (fast), middle (moderate), or end (slow).
  • Multiple Occurrences: If the key appears multiple times, the function will return the index of the first occurrence.
  • Key Not Present: If the key is not in the array at all, we go through the entire array and return -1 at the end.
  • Empty Array: If the array has no elements, there is nothing to check. So, we directly return -1.
  • Single Element Array: If the array has only one element, the answer will either be index 0 if it matches the key, or -1 if it doesn’t.

Why Use Linear Search?

While not the fastest for large arrays, linear search works well for small arrays or when the data is unsorted. It’s also very easy to implement and understand.

Overall, linear search is the go-to method when you need a quick, simple way to check if a value exists in an array without any advanced setup or sorting.

Visualization

Algorithm Steps

  1. Given an array arr and a target key.
  2. Iterate through the array from index 0 to n-1.
  3. For each element, check if arr[i] == key.
  4. If a match is found, return the index i.
  5. If no match is found after the loop ends, return -1.

Code

Python
JavaScript
Java
C++
C
def linear_search(arr, key):
    for i in range(len(arr)):
        if arr[i] == key:
            return i
    return -1

# Sample Input
arr = [10, 20, 30, 40, 50]
key = 30
print("Element found at index:", linear_search(arr, key))

Time Complexity

CaseTime ComplexityExplanation
Best CaseO(1)The target element is found at the very first index of the array.
Average CaseO(n)On average, the search will check half of the array before finding the target or confirming it doesn't exist.
Average CaseO(n)In the worst case, the algorithm will check every element in the array, either finding the target at the end or not finding it at all.

Space Complexity

O(1)

Explanation: The algorithm uses a constant amount of extra space—just a loop variable and the target value—regardless of the array size.

Detailed Step by Step Example

We are performing a linear search for the value 40 in the array.

{ "array": [10,20,30,40,50], "showIndices": true }
{ "array": ["key:", 40], "emptyIndices": [0], "highlightIndicesGreen": [1] }

Check index 0

Compare arr[0] = 10 with key = 40.

{ "array": [10,20,30,40,50], "showIndices": true, "highlightIndices": [0], "labels": {"0":"i"} }

No match. Continue to next index.

Check index 1

Compare arr[1] = 20 with key = 40.

{ "array": [10,20,30,40,50], "showIndices": true, "highlightIndices": [1], "labels": {"1":"i"} }

No match. Continue to next index.

Check index 2

Compare arr[2] = 30 with key = 40.

{ "array": [10,20,30,40,50], "showIndices": true, "highlightIndices": [2], "labels": {"2":"i"} }

No match. Continue to next index.

Check index 3

Compare arr[3] = 40 with key = 40.

Match found! Element 40 is equal to key 40. Return index 3.

{ "array": [10,20,30,40,50], "showIndices": true, "highlightIndicesGreen": [3], "labels": {"3":"i"} }


Welcome to ProgramGuru

Sign up to start your journey with us

Support ProgramGuru.org

You can support this website with a contribution of your choice.

When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.

PayPal

UPI

PhonePe QR

MALLIKARJUNA M