0
0
DSA Javascriptprogramming~10 mins

First and Last Occurrence of Element in DSA Javascript - Interactive Practice

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

Complete the code to find the first occurrence index of a target element in an array.

DSA Javascript
function firstOccurrence(arr, target) {
  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'
Anull
Barr
Ci
Dtarget
Attempts:
3 left
💡 Hint
Common Mistakes
Using the wrong variable for comparison like 'arr' or 'i'.
Returning the element instead of the index.
2fill in blank
medium

Complete the code to find the last occurrence index of a target element in an array.

DSA Javascript
function lastOccurrence(arr, target) {
  for (let i = arr.length - 1; i >= 0; i--) {
    if (arr[i] === [1]) {
      return i;
    }
  }
  return -1;
}
Drag options to blanks, or click blank then click option'
Ai
Bnull
Ctarget
Darr
Attempts:
3 left
💡 Hint
Common Mistakes
Using the wrong variable for comparison.
Looping forward instead of backward.
3fill in blank
hard

Fix the error in the code to correctly find the first occurrence of target in the array.

DSA Javascript
function firstOccurrence(arr, target) {
  let index = -1;
  for (let i = 0; i < arr.length; i++) {
    if (arr[i] === [1]) {
      index = i;
      break;
    }
  }
  return index;
}
Drag options to blanks, or click blank then click option'
Atarget
Barr[i]
C==
D===
Attempts:
3 left
💡 Hint
Common Mistakes
Using assignment '=' instead of comparison '==='.
Putting the wrong variable on the right side.
4fill in blank
hard

Fill both blanks to create a function that returns an object with first and last occurrence indices of target in arr.

DSA Javascript
function firstAndLastOccurrence(arr, target) {
  let first = -1;
  let last = -1;
  for (let i = 0; i < arr.length; i++) {
    if (arr[i] === [1]) {
      if (first === -1) {
        first = i;
      }
      last = [2];
    }
  }
  return { first, last };
}
Drag options to blanks, or click blank then click option'
Atarget
Bi
Cfirst
Darr[i]
Attempts:
3 left
💡 Hint
Common Mistakes
Assigning last to first instead of current index.
Comparing arr[i] to wrong variable.
5fill in blank
hard

Fill all three blanks to create a function that returns an object with first and last occurrence indices of target using a single pass.

DSA Javascript
function findOccurrences(arr, target) {
  let result = { first: -1, last: -1 };
  for (let i = 0; i < [1]; i++) {
    if (arr[i] === [2]) {
      if (result.first === -1) {
        result.first = i;
      }
      result.last = [3];
    }
  }
  return result;
}
Drag options to blanks, or click blank then click option'
Aarr.length
Btarget
Ci
Dresult.first
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong loop limit.
Comparing with wrong variable.
Assigning last to wrong value.