0
0
DSA Typescriptprogramming~30 mins

Linear Search Algorithm in DSA Typescript - Build from Scratch

Choose your learning style9 modes available
Linear Search Algorithm
📖 Scenario: You are helping a store manager find a specific product ID in the list of products available in the store.
🎯 Goal: Build a simple linear search algorithm to find the position of a product ID in an array of product IDs.
📋 What You'll Learn
Create an array called productIDs with exact values
Create a variable called targetID to hold the product ID to search
Use a for loop with variable i to search targetID in productIDs
Print the index of targetID if found, otherwise print -1
💡 Why This Matters
🌍 Real World
Stores and inventory systems often need to find if a product is available by checking product IDs one by one.
💼 Career
Understanding linear search helps in debugging and improving simple search tasks in software development and data handling.
Progress0 / 4 steps
1
Create the product ID list
Create an array called productIDs with these exact numbers: 101, 203, 405, 607, 809
DSA Typescript
Hint

Use square brackets [] to create an array and separate numbers with commas.

2
Set the target product ID
Create a variable called targetID and set it to 405
DSA Typescript
Hint

Use const to create a variable and assign the number 405.

3
Search for the target ID using linear search
Use a for loop with variable i to go through productIDs. Inside the loop, use an if statement to check if productIDs[i] equals targetID. If yes, print i and stop the loop.
DSA Typescript
Hint

Use a for loop from 0 to productIDs.length. Use === to compare values. Use break to stop the loop when found.

4
Print -1 if target not found
Modify the code to print -1 if targetID is not found in productIDs. Use a variable called foundIndex initialized to -1. Update it inside the loop if found. After the loop, print foundIndex.
DSA Typescript
Hint

Use a variable foundIndex set to -1 before the loop. Change it to i if found. Print it after the loop.