Binary TreesBinary Trees36
  1. 1Preorder Traversal of a Binary Tree using Recursion
  2. 2Preorder Traversal of a Binary Tree using Iteration
  3. 3Inorder Traversal of a Binary Tree using Recursion
  4. 4Inorder Traversal of a Binary Tree using Iteration
  5. 5Postorder Traversal of a Binary Tree Using Recursion
  6. 6Postorder Traversal of a Binary Tree using Iteration
  7. 7Level Order Traversal of a Binary Tree using Recursion
  8. 8Level Order Traversal of a Binary Tree using Iteration
  9. 9Reverse Level Order Traversal of a Binary Tree using Iteration
  10. 10Reverse Level Order Traversal of a Binary Tree using Recursion
  11. 11Find Height of a Binary Tree
  12. 12Find Diameter of a Binary Tree
  13. 13Find Mirror of a Binary Tree
  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
GraphsGraphs46
  1. 1Breadth-First Search in Graphs
  2. 2Depth-First Search in Graphs
  3. 3Number of Provinces in an Undirected Graph
  4. 4Connected Components in a Matrix
  5. 5Rotten Oranges Problem - BFS in Matrix
  6. 6Flood Fill Algorithm - Graph Based
  7. 7Detect Cycle in an Undirected Graph using DFS
  8. 8Detect Cycle in an Undirected Graph using BFS
  9. 9Distance of Nearest Cell Having 1 - Grid BFS
  10. 10Surrounded Regions in Matrix using Graph Traversal
  11. 11Number of Enclaves in Grid
  12. 12Word Ladder - Shortest Transformation using Graph
  13. 13Word Ladder II - All Shortest Transformation Sequences
  14. 14Number of Distinct Islands using DFS
  15. 15Check if a Graph is Bipartite using DFS
  16. 16Topological Sort Using DFS
  17. 17Topological Sort using Kahn's Algorithm
  18. 18Cycle Detection in Directed Graph using BFS
  19. 19Course Schedule - Task Ordering with Prerequisites
  20. 20Course Schedule 2 - Task Ordering Using Topological Sort
  21. 21Find Eventual Safe States in a Directed Graph
  22. 22Alien Dictionary Character Order
  23. 23Shortest Path in Undirected Graph with Unit Distance
  24. 24Shortest Path in DAG using Topological Sort
  25. 25Dijkstra's Algorithm Using Set - Shortest Path in Graph
  26. 26Dijkstra’s Algorithm Using Priority Queue
  27. 27Shortest Distance in a Binary Maze using BFS
  28. 28Path With Minimum Effort in Grid using Graphs
  29. 29Cheapest Flights Within K Stops - Graph Problem
  30. 30Number of Ways to Reach Destination in Shortest Time - Graph Problem
  31. 31Minimum Multiplications to Reach End - Graph BFS
  32. 32Bellman-Ford Algorithm for Shortest Paths
  33. 33Floyd Warshall Algorithm for All-Pairs Shortest Path
  34. 34Find the City With the Fewest Reachable Neighbours
  35. 35Minimum Spanning Tree in Graphs
  36. 36Prim's Algorithm for Minimum Spanning Tree
  37. 37Disjoint Set (Union-Find) with Union by Rank and Path Compression
  38. 38Kruskal's Algorithm - Minimum Spanning Tree
  39. 39Minimum Operations to Make Network Connected
  40. 40Most Stones Removed with Same Row or Column
  41. 41Accounts Merge Problem using Disjoint Set Union
  42. 42Number of Islands II - Online Queries using DSU
  43. 43Making a Large Island Using DSU
  44. 44Bridges in Graph using Tarjan's Algorithm
  45. 45Articulation Points in Graphs
  46. 46Strongly Connected Components using Kosaraju's Algorithm

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.

  • In linear search, we check each element one by one from left to right.
  • If the key is found, return the index of the first occurrence of the key.
  • If the key is not present in the array, return -1.

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

Examples

Input Array Key Output Description
[10, 20, 30, 40, 50] 30 2 30 is present at index 2Visualization
[5, 8, 12, 8, 20] 8 1 First occurrence of 8 is at index 1Visualization
[1, 2, 3, 4, 5] 6 -1 6 is not in the arrayVisualization
[] 5 -1 Array is empty, so nothing to searchVisualization
[42] 42 0 Single element matches the keyVisualization
[42] 99 -1 Single element does not matchVisualization
[1, 1, 1, 1] 1 0 All elements match, but return the first indexVisualization

Visualization Player

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.

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.
Worst 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"} }