Skip to content

Conversation

VeronicaM
Copy link
Owner

@VeronicaM VeronicaM commented May 8, 2020

All PRs

  • I have self-reviewed my code
  • I have written tests which cover new and changed functionality
  • All tests pass
  • I have commented on difficult to understand code

Where Relevant

  • I have compared and validated my UI changes against the designs
  • I've updated relevant documentation e.g. README

Description

What is this PR about ?

Implement using iteration and recursion a function to find the index for a value in a given array from a given start index.

What was implemented ?

  1. Iterative approach:
  • Iterate over array from the startIndex with a for loop
  • check if the value at current index is equal to the value we are looking for and return currentIndex if true.

Runtime complexity : O(n - startindex), n is the number of elements in the array
Space complexity: O(1)

  1. Recursive approach:
  • Identify base case as when the startIndex has reached the length of the array. This implies the whole array has been traversed and the value we were looking for hasn't been found, therefore -1 is returned.
  • Identify recursive case as simply incrementing the startIndex to access the next value in the array if the value has not been identified yet.

Runtime complexity : O(n - startIndex)
Space complexity: O(n - startIndex)

What did you learn ?

Being able to follow what happens in a recursive algorithm gets a lot easier with practice, also writing it in an iterative form first and then transforming it in a recursive solution helps a lot to identify the base case and the recursive case.

Recursion usually has worse Space complexity than iterative solutions, therefore it's good to use only if really needed, i.e. the solution cannot be solved iteratively with a better runtime and space complexity.

What links/documents relate to this PR ?

Testing

Steps required to test

  • cd interviews/recursion/first-occurrence-of-number
  • run node first-occurrence-of-number.js

All tests should pass
Test cases can be found in interviews/recursion/first-occurrence-of-number/testData

@VeronicaM VeronicaM merged commit 91bbd15 into master May 8, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant