66 lines
1.6 KiB
Markdown
66 lines
1.6 KiB
Markdown
# Find First Occurrence of a Number in an Array
|
|
|
|
## Question
|
|
|
|
[Sloth Bytes | 2024-07-02](https://slothbytes.beehiiv.com/p/debugging?utm_source=slothbytes.beehiiv.com&utm_medium=newsletter&utm_campaign=debugging-techniques-you-should-know)
|
|
|
|
```
|
|
Binary Search Practice
|
|
Given a sorted array of integers and a target integer, find the first occurrence of the target and return its index.
|
|
|
|
Return -1 if the target is not in the array.
|
|
|
|
Examples
|
|
#Input:
|
|
|
|
arr = [1, 3, 3, 3, 3, 6, 10, 10, 10, 100]
|
|
|
|
target = 3
|
|
|
|
find_first_occurrence(arr,target) # Return 1
|
|
|
|
#Explanation: The first occurrence of 3 is at index 1.
|
|
#Input:
|
|
|
|
arr = [2, 3, 5, 7, 11, 13, 17, 19]
|
|
|
|
target = 6
|
|
find_first_occurrence(arr,target) # Return -1
|
|
|
|
#Explanation: 6 does not exist in the array.
|
|
```
|
|
|
|
## Description
|
|
|
|
This utility takes a user input of array items and target input. The code finds the first occurrence of the target number in the given array which will be sorted.
|
|
|
|
## Table of Contents
|
|
|
|
- [Installation](#installation)
|
|
- [Usage](#usage)
|
|
|
|
## Installation
|
|
|
|
To use the code in this repository, you need to have [Node.js](https://nodejs.org/en) installed on your machine. Clone the repository to your local system using the following command:
|
|
|
|
```
|
|
git clone https://github.com/afiqzudinhadi/first-occurrence.git
|
|
```
|
|
|
|
Install the required dependencies by running the following command:
|
|
|
|
```
|
|
npm install
|
|
```
|
|
|
|
## Usage
|
|
|
|
1. Navigate to the repository's root directory.
|
|
2. Open terminal or command prompt.
|
|
3. Run the following command to execute the code:
|
|
|
|
```
|
|
npm run index
|
|
```
|
|
|
|
4. Follow the on-screen instructions to input the array or string and the element you want to find the first occurrence of.
|