Skip to content

25-reverse-nodes-in-k-groups: Add Iterative Solution #590

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Aug 10, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
58 changes: 57 additions & 1 deletion java/25-Reverse-Nodes-in-k-Group.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,20 @@
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/

//This recursive approach is super intuitive taken from leetcode discuss.

class Solution {
// Time Complexity: O(n)
// Extra Space Complexity: O(n)

class Solution1 {

public ListNode reverseKGroup(ListNode head, int k) {
ListNode cur = head;
Expand All @@ -22,3 +36,45 @@ public ListNode reverseKGroup(ListNode head, int k) {
return head;
}
}

// An iterative approach

// Time Complexity: O(n)
// Extra Space Complexity: O(1)

class Solution2 {
public ListNode reverseKGroup(ListNode head, int k) {
ListNode dummy = new ListNode(0, head);
ListNode curr = head;
ListNode prev = dummy;
ListNode temp = null;

int count = k;

while (curr != null) {
if (count > 1) {
temp = prev.next;
prev.next = curr.next;
curr.next = curr.next.next;
prev.next.next = temp;

count--;
} else {
prev = curr;
curr = curr.next;

ListNode end = curr;

for(int i = 0; i < k; ++i) {
if (end == null) {
return dummy.next;
}
end = end.next;
}
count = k;
}
}

return dummy.next;
}
}