File tree Expand file tree Collapse file tree 4 files changed +83
-0
lines changed
kotlin/Fast and Slow Pointers Expand file tree Collapse file tree 4 files changed +83
-0
lines changed Original file line number Diff line number Diff line change
1
+ fun happyNumber (n : Int ): Boolean {
2
+ var slow = n
3
+ var fast = n
4
+ while (true ) {
5
+ slow = getNextNum(slow)
6
+ fast = getNextNum(getNextNum(fast))
7
+ if (fast == 1 ) {
8
+ return true
9
+ // If the fast and slow pointers meet, a cycle is detected.
10
+ // Hence, 'n' is not a happy number.
11
+ } else if (fast == slow) {
12
+ return false
13
+ }
14
+ }
15
+ }
16
+
17
+ fun getNextNum (x : Int ): Int {
18
+ var nextNum = 0
19
+ var num = x
20
+ while (num > 0 ) {
21
+ // Extract the last digit of 'x'.
22
+ val digit = num % 10
23
+ // Truncate (remove) the last digit from 'x' using floor
24
+ // division.
25
+ num / = 10
26
+ // Add the square of the extracted digit to the sum.
27
+ nextNum + = digit * digit
28
+ }
29
+ return nextNum
30
+ }
Original file line number Diff line number Diff line change
1
+ /*
2
+ Definition of ListNode:
3
+ data class ListNode(var value: Int, var next: ListNode? = null)
4
+ */
5
+
6
+ fun linkedListLoop (head : ListNode ? ): Boolean {
7
+ var slow = head
8
+ var fast = head
9
+ // Check both 'fast' and 'fast.next' to avoid null pointer
10
+ // exceptions when we perform 'fast.next' and 'fast.next.next'.
11
+ while (fast != null && fast.next != null ) {
12
+ slow = slow!! .next
13
+ fast = fast.next!! .next
14
+ if (fast == slow) {
15
+ return true
16
+ }
17
+ }
18
+ return false
19
+ }
Original file line number Diff line number Diff line change
1
+ /*
2
+ Definition of ListNode:
3
+ data class ListNode(var value: Int, var next: ListNode? = null)
4
+ */
5
+
6
+ fun linkedListLoopNaive (head : ListNode ? ): Boolean {
7
+ val visited = mutableSetOf<ListNode >()
8
+ var curr = head
9
+ while (curr != null ) {
10
+ // Cycle detected if the current node has already been visited.
11
+ if (visited.contains(curr)) {
12
+ return true
13
+ }
14
+ visited.add(curr)
15
+ curr = curr.next
16
+ }
17
+ return false
18
+ }
Original file line number Diff line number Diff line change
1
+ /*
2
+ Definition of ListNode:
3
+ data class ListNode(var value: Int, var next: ListNode? = null)
4
+ */
5
+
6
+ fun linkedListMidpoint (head : ListNode ? ): ListNode ? {
7
+ var slow = head
8
+ var fast = head
9
+ // When the fast pointer reaches the end of the list, the slow
10
+ // pointer will be at the midpoint of the linked list.
11
+ while (fast != null && fast.next != null ) {
12
+ slow = slow!! .next
13
+ fast = fast.next!! .next
14
+ }
15
+ return slow
16
+ }
You can’t perform that action at this time.
0 commit comments