Grokking Amazon Coding Interview
Vote
0% completed
Hidden Document
Hidden Document Content Hidden Document Content Hidden Document Content Hidden Document Content Hidden Document Content Hidden Document Content Hidden Document Content Hidden Document Content Hidden Document Content Hidden Document Content Hidden Document Content Hidden Document Content Hidden Document Content Hidden Document Content Hidden Document Content Hidden Document Content Hidden Document Content Hidden Document Content Hidden Document Content Hidden Document Content Hidden Document Content Hidden Document Content Hidden Document Content Hidden Document Content
.....
.....
.....
Like the course? Get enrolled and start learning!
senthil kumar
· 2 years ago
Kindly add the main method and print method to avoid confusion and add clarity.
public void printList(ListNode head) {
ListNode current = head;
while (current != null) {
System.out.print(current.val + " ");
current = current.next;
}
System.out.println();
}
public static void main(String[] args) {
Solution solution = new Solution();
// Test Example 1
ListNode head1 = new ListNode(1, new ListNode(1, new ListNode(2)));
ListNode result1 = solution.deleteDuplicates(head1); // Expected: 1 -> 2
solution.printList(result1);
// Test Example 2
ListNode head2 = new ListNode(1, new ListNode(2, new ListNode(2, new ListNode(3))));
ListNode result2 = solution
D
Daven L
· 2 years ago
class Solution: def deleteDuplicates(self, head): # so I dont lose my original head, I set a variable current current = head # traverse through LL, ensuring curr and curr.next exist while current and current.next is not None: # prev becomes the value to which we compare other values to prev = current current = current.next # we move current until current.val no longer matches prev value # ensure we don't hit None by checking that current also exists while current and prev.val == current.val: current = current.next # whether current is now None or some number that is not prev.val, we set prev.next prev.next = current return
Divyanshu Varma
· a year ago
/* * We should delete unused bypassed nodes otherwise * if you had n nodes to begin with and deleted m nodes * you will still be consuming n nodes worth of memory. */ ListNode* deleteDuplicates(ListNode* head) { if(!head or !head->next) { // base case return head; } auto curr = head, ahead = head->next; // adjacent nodes while(ahead) { if(curr->val == ahead->val) { auto temp = ahead; curr->next = ahead->next; // skip duplicate ahead = ahead->next; delete temp; // delete unused node } else { curr = curr->next; ahead = ahead->next; } } return head; }