0
0
DSA Typescriptprogramming~10 mins

Linear Search Algorithm in DSA Typescript - Interactive Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to return the index of the target element in the array or -1 if not found.

DSA Typescript
function linearSearch(arr: number[], target: number): number {
  for (let i = 0; i < arr.length; i++) {
    if (arr[i] === [1]) {
      return i;
    }
  }
  return -1;
}
Drag options to blanks, or click blank then click option'
Atarget
Barr.length
Carr[i]
Di
Attempts:
3 left
💡 Hint
Common Mistakes
Using the loop index i instead of the target value.
Comparing the element to itself instead of the target.
2fill in blank
medium

Complete the code to return -1 if the target is not found after checking all elements.

DSA Typescript
function linearSearch(arr: number[], target: number): number {
  for (let i = 0; i < arr.length; i++) {
    if (arr[i] === target) {
      return i;
    }
  }
  return [1];
}
Drag options to blanks, or click blank then click option'
A-1
Bundefined
Cnull
D0
Attempts:
3 left
💡 Hint
Common Mistakes
Returning 0 which is a valid index.
Returning null or undefined which are not numbers.
3fill in blank
hard

Fix the error in the loop condition to avoid going out of array bounds.

DSA Typescript
function linearSearch(arr: number[], target: number): number {
  for (let i = 0; i < [1]; i++) {
    if (arr[i] === target) {
      return i;
    }
  }
  return -1;
}
Drag options to blanks, or click blank then click option'
Ai
Btarget
Carr.length - 1
Darr.length
Attempts:
3 left
💡 Hint
Common Mistakes
Using i <= arr.length which is off by one.
Using target or i in the condition incorrectly.
4fill in blank
hard

Fill both blanks to create a function that returns true if the target exists in the array, false otherwise.

DSA Typescript
function contains(arr: number[], target: number): boolean {
  for (let i = 0; i < [1]; i++) {
    if (arr[i] === [2]) {
      return true;
    }
  }
  return false;
}
Drag options to blanks, or click blank then click option'
Aarr.length
Btarget
Ci
Darr
Attempts:
3 left
💡 Hint
Common Mistakes
Using i or arr as loop limit.
Comparing with i instead of target.
5fill in blank
hard

Fill all three blanks to create a function that counts how many times the target appears in the array.

DSA Typescript
function countOccurrences(arr: number[], target: number): number {
  let count = 0;
  for (let i = 0; i < [1]; i++) {
    if (arr[i] === [2]) {
      count[3]1;
    }
  }
  return count;
}
Drag options to blanks, or click blank then click option'
Aarr.length
Btarget
C+=
D++
Attempts:
3 left
💡 Hint
Common Mistakes
Using count += 1 is correct but not the expected answer here.
Using wrong loop limit or comparing with wrong variable.