Skip to content
Open
Show file tree
Hide file tree
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
45 changes: 45 additions & 0 deletions LinkedListCycleII.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
// Brute force O(n) time, O(n) space
// public class Solution {
// public boolean detectCycle(ListNode head) {
// Set<ListNode> set = new HashSet<>();

// while (head != null) {
// if (set.contains(head)) {
// return head;
// }
// set.add(head);
// head = head.next;
// }
// return null;
// }
// }

// Slow and fast O(n) time, O(1) space
class Solution {
public ListNode detectCycle(ListNode head) {
ListNode slow = head;
ListNode fast = head;
boolean hasCycle = false;

// fast != null needed for even length, fast.next != null needed for odd length
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;

if (slow == fast) {
hasCycle = true;
break;
}
}

if (!hasCycle) return null;

slow = head;

while (slow != fast) {
slow = slow.next;
fast = fast.next;
}
return slow;
}
}
26 changes: 26 additions & 0 deletions RemoveNthNode.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
// Two pointers O(n) time, O(1) space
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode dummy = new ListNode(-1);
dummy.next = head;

ListNode slow = dummy;
ListNode fast = dummy;

int count = 0;
while (count <= n) {
fast = fast.next;
count++;
}
// after loop we have difference of n between slow and fast

while (fast != null) {
slow = slow.next;
fast = fast.next;
}
slow.next = slow.next.next; // deleting by skipping node and reassigning to node after

return dummy.next; // return head which is node to remove
}
}

26 changes: 26 additions & 0 deletions ReverseLinkedList.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
// O(n) time, O(1) space
class Solution {
public ListNode reverseList(ListNode head) {
if (head == null || head.next == null) return head;

ListNode prev = null;
ListNode curr = head;

while (curr != null) {
ListNode temp = curr.next;
curr.next = prev;
prev = curr;
curr = temp;
}
return prev;
}
}

class ListNode {
int val;
ListNode next;
ListNode() {}
ListNode(int val) { this.val = val; }
ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}