Skip to content

Commit ddf8277

Browse files
authored
Merge pull request #6 from devvsakib/devvsakib
largest num index, interview q
2 parents d898768 + 71e4b21 commit ddf8277

File tree

2 files changed

+69
-0
lines changed

2 files changed

+69
-0
lines changed
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
# 0004 LargestNumIndex ( L-B )
2+
3+
## Problem
4+
5+
Given an array of integers, find the index of the largest number in the array.
6+
7+
## Test Cases
8+
9+
- Input: [12, 3, 1, 54, 65, 4, 9], Output: 4
10+
- Input: [12, 3, 1, 54], Output: 3
11+
12+
## Solution
13+
14+
```javascript
15+
function largestNumIndex(arr) {
16+
let largestNum = arr[0];
17+
let largestNumIndex = 0;
18+
for (let i = 1; i < arr.length; i++) {
19+
if (arr[i] > largestNum) {
20+
largestNum = arr[i];
21+
largestNumIndex = i;
22+
}
23+
}
24+
return largestNumIndex;
25+
}
26+
const arr = [12, 3, 1, 54, 65, 4, 9]
27+
console.log(lgNumIndex(arr)); // expected 4, largestnum - 65
28+
```
29+
30+
## How it works
31+
32+
- The function takes an array as a parameter.
33+
- It creates a variable called largestNum and assigns it a value of the first element of the array.
34+
- It creates a variable called largestNumIndex and assigns it a value of 0.
35+
- It creates a for loop that starts from 1 and ends at the length of the array.
36+
- It checks if the value of the current index is greater than the value of largestNum.
37+
- If it is, it assigns the value of the current index to largestNum and assigns the value of i to largestNumIndex.
38+
- It returns the value of largestNumIndex.
39+
40+
## References
41+
42+
- [Wikipedia](https://en.wikipedia.org/wiki/For_loop)
43+
- [GeeksforGeeks](https://www.geeksforgeeks.org/for-loop-in-javascript/)
44+
- [StackOverflow](https://stackoverflow.com/questions/1669190/javascript-min-max-array-values)
45+
46+
## Problem Added By
47+
48+
- [GitHub](https://www.github.com/devvsakib)
49+
- [LinkedIn](https://www.linkedin.com/in/devvsakib)
50+
- [Twitter](https://twitter.com/devvsakib)
51+
52+
## Contributing
53+
54+
Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.
55+
56+
Please make sure to update tests as appropriate.
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
function lgNumIndex(array) {
2+
let largestNum = array[0];
3+
4+
for (const ele of array) {
5+
if (largestNum < ele) {
6+
largestNum = ele
7+
}
8+
}
9+
let indexofNum = array.indexOf(largestNum);
10+
return indexofNum
11+
}
12+
const arr = [12, 3, 1, 54, 65, 4, 9]
13+
console.log(lgNumIndex(arr)); // expected 4

0 commit comments

Comments
 (0)