Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 40dcbe9

Browse files
author
Swastikyadav
committed
move midPoint question into the folder
1 parent f78d6a0 commit 40dcbe9

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

‎DsAlgo-Questions/19-midPoint.js

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
/*
2+
Return the 'middle' node of a linked list.
3+
If the list has an even number of elements, return the node at the end of the first half of the list.
4+
5+
*Do not* use a counter variable, *do not* retrive the size of the list, and only iterate through the list one time.
6+
7+
--Example
8+
9+
const l = new LinkedList();
10+
l.insertLast('a');
11+
l.insertLast('b');
12+
l.insertLast('c');
13+
14+
midPoint(l); // returns { data: 'b' };
15+
*/
16+
17+
// -----------------------------------------------
18+
19+
const oddArr = [4, 7, 5, 9, 2, 47, 11]; // 9
20+
const evenArr = [4, 7, 5, 9, 2, 47] // 5
21+
22+
function midPoint(arr) {
23+
let slow = 0;
24+
let fast = 0;
25+
26+
while (arr[fast + 2]) {
27+
slow += 1;
28+
fast += 2;
29+
}
30+
31+
return arr[slow];
32+
}
33+
34+
console.log(midPoint(oddArr)); // 9
35+
console.log(midPoint(evenArr)); // 5
36+
37+
// -----------------------------------------------
38+
39+
// Solution technique:
40+
// We will use 2 pointer variables 'slow' and 'fast'.
41+
// With each iteration slow will move ahead by 1 and fast will move ahead by 2.
42+
// 'fast' will move twice as fast as 'slow'.
43+
// So, when 'fast' will point to the last node, 'slow' must be pointing to the middle node.

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /