SlideShare a Scribd company logo
1 of 8
Download to read offline
TOP
INTERVIEW
QUESTIONS
EASYCOLLECTIONS
LINKEDLIST
Sunil Yadav
Linked List problems are relatively easy to master. Do
not forget the Two-pointer technique, which not only
applicable to Array problems but also Linked List
problems as well.
Another technique to greatly simplify coding in linked
list problems is the dummy node trick.
We recommend: Reverse Linked List, Merge Two
Sorted Lists and Linked List Cycle.
For additional challenge, solve these problems
recursively: Reverse Linked List, Palindrome Linked List
and Merge Two Sorted Lists.
IntroductION
Delete Node in a Linked List
Write a function to delete a node (except the tail) in a singly linked list, given only
access to that node.
Given linked list -- head = [4,5,1,9], which looks like following:
Example 1:
Input: head = [4,5,1,9], node = 5
Output: [4,1,9]
Explanation: You are given the second node with value 5, the
linked list should become 4 -> 1 -> 9 after calling your
function.
Example 2:
Input: head = [4,5,1,9], node = 1
Output: [4,5,9]
Explanation: You are given the third node with value 1, the
linked list should become 4 -> 5 -> 9 after calling your
function.
Note:
• The linked list will have at least two elements.
• All of the nodes' values will be unique.
• The given node will not be the tail and it will always be a valid node of the
linked list.
• Do not return anything from your function.
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public void deleteNode(ListNode node) {
ListNode Prev = null;
while(node.next!=null){
node.val = node.next.val;
Prev = node;
node = node.next;
}
if(Prev!=null)
Prev.next = null;
}
}
Remove Nth Node From End of List
Given a linked list, remove the n-th node from the end of list and return its head.
Example:
Given linked list: 1->2->3->4->5, and n = 2.
After removing the second node from the end, the linked list
becomes 1->2->3->5.
Note:
Given n will always be valid.
Follow up:
Could you do this in one pass?
•
/**
* 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; }
* }
*/
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode Prev = null;
ListNode fN = head;
ListNode slow = head;
int counter = 1;
while(head!=null){
if(counter>n){
Prev = slow;
slow = slow.next;
}
counter++;
head = head.next;
}
if(Prev!=null){
if(slow!=null)
Prev.next = slow.next;
else
Prev.next = null;
}
if(Prev == null){
return fN.next;
}
return fN;
}
}
 Reverse Linked List
Reverse a singly linked list.
Example:
Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL
Follow up:
A linked list can be reversed either iteratively or recursively. Could you implement
both?
•
/**
* 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; }
* }
*/
class Solution {
public ListNode reverseList(ListNode head) {
ListNode root = head;
ListNode Prev = null;
while(head!=null){
ListNode nextNode = head.next;
head.next = Prev;
Prev = head;
head = nextNode;
}
return Prev;
}
}
Merge Two Sorted Lists
Merge two sorted linked lists and return it as a new sorted list. The new list should
be made by splicing together the nodes of the first two lists.
Example:
Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4
/**
* 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; }
* }
*/
class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode x = l1;
ListNode y = l2;
ListNode result = new ListNode(-1);
ListNode fR = result;
while(x!=null && y!=null){
if(x.val <= y.val){
result.next = new ListNode(x.val);
x = x.next;
}else{
result.next = new ListNode(y.val);
y = y.next;
}
result = result.next;
}
if(x!=null){
result.next = x;
result = result.next;
}
if(y!=null){
result.next = y;
result = result.next;
}
return fR.next;
}
Palindrome Linked List
Given a singly linked list, determine if it is a palindrome.
Example 1:
Input: 1->2
Output: false
Example 2:
Input: 1->2->2->1
Output: true
Follow up:

Could you do it in O(n) time and O(1) space?
/**
* 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; }
* }
*/
class Solution {
public boolean isPalindrome(ListNode head) {
ListNode slow = head;
ListNode fast = head;
while(fast!=null && fast.next!=null){
slow = slow.next;
fast = fast.next.next;
}
Stack<ListNode> stack = new Stack<>();
// Slow is at Middle Position
while(slow!=null){
stack.push(slow);
slow = slow.next;
}
while(!stack.isEmpty()){
if(head.val!=stack.pop().val){
return false;
}
head = head.next;
}
return true;
}
}
Linked List Cycle
Given a linked list, determine if it has a cycle in it.
To represent a cycle in the given linked list, we use an integer pos which
represents the position (0-indexed) in the linked list where tail connects to.
If pos is -1, then there is no cycle in the linked list.
Example 1:
Input: head = [3,2,0,-4], pos = 1
Output: true
Explanation: There is a cycle in the linked list, where tail
connects to the second node.
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public boolean hasCycle(ListNode head) {
if(head == null){
return false;
}
ListNode slow = head;
ListNode fast = head.next;
while(true){
if(slow==null || fast==null){
return false;
}
if(slow==fast){
return true;
}
slow = slow.next;
if(fast.next==null){
return false;
}
fast = fast.next.next;
}
}
}

More Related Content

What's hot

Math functions, relations, domain & range
Math functions, relations, domain & rangeMath functions, relations, domain & range
Math functions, relations, domain & rangeRenee Scott
 
Relations and Functions
Relations and FunctionsRelations and Functions
Relations and Functionstoni dimella
 
Module 1 Lesson 1 Remediation Notes
Module 1 Lesson 1 Remediation NotesModule 1 Lesson 1 Remediation Notes
Module 1 Lesson 1 Remediation Notestoni dimella
 
Relations and functions
Relations and functionsRelations and functions
Relations and functionsHeather Scott
 
Relations and functions remediation notes
Relations and functions remediation notesRelations and functions remediation notes
Relations and functions remediation notescarolinevest77
 
Storyboard math
Storyboard mathStoryboard math
Storyboard mathshandex
 
8.1 Relations And Functions
8.1 Relations And Functions8.1 Relations And Functions
8.1 Relations And FunctionsJessca Lundin
 
L1 functions, domain &amp; range
L1 functions, domain &amp; rangeL1 functions, domain &amp; range
L1 functions, domain &amp; rangeJames Tagara
 
7_Intro_to_Functions
7_Intro_to_Functions7_Intro_to_Functions
7_Intro_to_Functionsnechamkin
 
Relations & Functions
Relations & FunctionsRelations & Functions
Relations & FunctionsJ Edwards
 
Functions domainrange
Functions domainrangeFunctions domainrange
Functions domainrangeDreams4school
 
Domain and range_ppt (1)
Domain and range_ppt (1)Domain and range_ppt (1)
Domain and range_ppt (1)Bernard Mendoza
 
Functions domain-range
Functions domain-rangeFunctions domain-range
Functions domain-rangeOlaug S
 
Relations and functions
Relations and functionsRelations and functions
Relations and functionsThabani Masoka
 
Relations and Functions
Relations and FunctionsRelations and Functions
Relations and Functionsr3h1na
 

What's hot (20)

7 functions
7   functions7   functions
7 functions
 
Math functions, relations, domain & range
Math functions, relations, domain & rangeMath functions, relations, domain & range
Math functions, relations, domain & range
 
Relations and Functions
Relations and FunctionsRelations and Functions
Relations and Functions
 
Module 1 Lesson 1 Remediation Notes
Module 1 Lesson 1 Remediation NotesModule 1 Lesson 1 Remediation Notes
Module 1 Lesson 1 Remediation Notes
 
Relations and functions
Relations and functionsRelations and functions
Relations and functions
 
Relations and functions remediation notes
Relations and functions remediation notesRelations and functions remediation notes
Relations and functions remediation notes
 
Storyboard math
Storyboard mathStoryboard math
Storyboard math
 
8.1 Relations And Functions
8.1 Relations And Functions8.1 Relations And Functions
8.1 Relations And Functions
 
Relations and functions
Relations and functionsRelations and functions
Relations and functions
 
Relations &amp; functions
Relations &amp; functionsRelations &amp; functions
Relations &amp; functions
 
L1 functions, domain &amp; range
L1 functions, domain &amp; rangeL1 functions, domain &amp; range
L1 functions, domain &amp; range
 
7_Intro_to_Functions
7_Intro_to_Functions7_Intro_to_Functions
7_Intro_to_Functions
 
Relations & Functions
Relations & FunctionsRelations & Functions
Relations & Functions
 
Functions domainrange
Functions domainrangeFunctions domainrange
Functions domainrange
 
Domain and range_ppt (1)
Domain and range_ppt (1)Domain and range_ppt (1)
Domain and range_ppt (1)
 
Functions domain-range
Functions domain-rangeFunctions domain-range
Functions domain-range
 
Relations and functions
Relations and functionsRelations and functions
Relations and functions
 
Relations and Functions
Relations and FunctionsRelations and Functions
Relations and Functions
 
Functions
FunctionsFunctions
Functions
 
Ml lesson 4 8
Ml lesson 4 8Ml lesson 4 8
Ml lesson 4 8
 

Similar to Linked List Leetcode - Easy Collections - Interview Questions Java

Lecture 4 data structures and algorithms
Lecture 4 data structures and algorithmsLecture 4 data structures and algorithms
Lecture 4 data structures and algorithmsAakash deep Singhal
 
using the single linked list code written in the class or in the lab,.pdf
using the single linked list code written in the class or in the lab,.pdfusing the single linked list code written in the class or in the lab,.pdf
using the single linked list code written in the class or in the lab,.pdfRBMADU
 
Data Structure Lecture 6
Data Structure Lecture 6Data Structure Lecture 6
Data Structure Lecture 6Teksify
 
Problem 1 Create Node class (or use what you have done in Lab4)• .pdf
Problem 1 Create Node class (or use what you have done in Lab4)• .pdfProblem 1 Create Node class (or use what you have done in Lab4)• .pdf
Problem 1 Create Node class (or use what you have done in Lab4)• .pdfmumnesh
 
Lec-4_Linked-List (1).pdf
Lec-4_Linked-List (1).pdfLec-4_Linked-List (1).pdf
Lec-4_Linked-List (1).pdfKylaMaeGarcia1
 
Data Structure and Algorithm Lesson 2.pptx
Data Structure and Algorithm Lesson 2.pptxData Structure and Algorithm Lesson 2.pptx
Data Structure and Algorithm Lesson 2.pptxJoannahClaireAlforqu
 
Data Structures in C++I am really new to C++, so links are really .pdf
Data Structures in C++I am really new to C++, so links are really .pdfData Structures in C++I am really new to C++, so links are really .pdf
Data Structures in C++I am really new to C++, so links are really .pdfrohit219406
 
Java AssignmentUsing the ListNode.java file below Write method.pdf
Java AssignmentUsing the ListNode.java file below Write method.pdfJava AssignmentUsing the ListNode.java file below Write method.pdf
Java AssignmentUsing the ListNode.java file below Write method.pdfambersushil
 
Write a function to merge two doubly linked lists. The input lists ha.pdf
Write a function to merge two doubly linked lists. The input lists ha.pdfWrite a function to merge two doubly linked lists. The input lists ha.pdf
Write a function to merge two doubly linked lists. The input lists ha.pdfinfo706022
 
here is the starter code public class LinkedListPracticeLab.pdf
here is the starter code public class LinkedListPracticeLab.pdfhere is the starter code public class LinkedListPracticeLab.pdf
here is the starter code public class LinkedListPracticeLab.pdfgeetakannupillai1
 
VCE Unit 02 (1).pptx
VCE Unit 02 (1).pptxVCE Unit 02 (1).pptx
VCE Unit 02 (1).pptxskilljiolms
 

Similar to Linked List Leetcode - Easy Collections - Interview Questions Java (20)

linked-list.ppt
linked-list.pptlinked-list.ppt
linked-list.ppt
 
Abstract data types
Abstract data typesAbstract data types
Abstract data types
 
Lecture 4 data structures and algorithms
Lecture 4 data structures and algorithmsLecture 4 data structures and algorithms
Lecture 4 data structures and algorithms
 
using the single linked list code written in the class or in the lab,.pdf
using the single linked list code written in the class or in the lab,.pdfusing the single linked list code written in the class or in the lab,.pdf
using the single linked list code written in the class or in the lab,.pdf
 
3.linked list
3.linked list3.linked list
3.linked list
 
Data Structure Lecture 6
Data Structure Lecture 6Data Structure Lecture 6
Data Structure Lecture 6
 
Unit - 2.pdf
Unit - 2.pdfUnit - 2.pdf
Unit - 2.pdf
 
Problem 1 Create Node class (or use what you have done in Lab4)• .pdf
Problem 1 Create Node class (or use what you have done in Lab4)• .pdfProblem 1 Create Node class (or use what you have done in Lab4)• .pdf
Problem 1 Create Node class (or use what you have done in Lab4)• .pdf
 
Linked list
Linked list Linked list
Linked list
 
linked list
linked list linked list
linked list
 
Lec-4_Linked-List (1).pdf
Lec-4_Linked-List (1).pdfLec-4_Linked-List (1).pdf
Lec-4_Linked-List (1).pdf
 
Data Structure and Algorithm Lesson 2.pptx
Data Structure and Algorithm Lesson 2.pptxData Structure and Algorithm Lesson 2.pptx
Data Structure and Algorithm Lesson 2.pptx
 
COL106_Assignments.pdf
COL106_Assignments.pdfCOL106_Assignments.pdf
COL106_Assignments.pdf
 
Data Structures in C++I am really new to C++, so links are really .pdf
Data Structures in C++I am really new to C++, so links are really .pdfData Structures in C++I am really new to C++, so links are really .pdf
Data Structures in C++I am really new to C++, so links are really .pdf
 
Java AssignmentUsing the ListNode.java file below Write method.pdf
Java AssignmentUsing the ListNode.java file below Write method.pdfJava AssignmentUsing the ListNode.java file below Write method.pdf
Java AssignmentUsing the ListNode.java file below Write method.pdf
 
Stack q ll algo
Stack q ll algoStack q ll algo
Stack q ll algo
 
Write a function to merge two doubly linked lists. The input lists ha.pdf
Write a function to merge two doubly linked lists. The input lists ha.pdfWrite a function to merge two doubly linked lists. The input lists ha.pdf
Write a function to merge two doubly linked lists. The input lists ha.pdf
 
Algo>ADT list & linked list
Algo>ADT list & linked listAlgo>ADT list & linked list
Algo>ADT list & linked list
 
here is the starter code public class LinkedListPracticeLab.pdf
here is the starter code public class LinkedListPracticeLab.pdfhere is the starter code public class LinkedListPracticeLab.pdf
here is the starter code public class LinkedListPracticeLab.pdf
 
VCE Unit 02 (1).pptx
VCE Unit 02 (1).pptxVCE Unit 02 (1).pptx
VCE Unit 02 (1).pptx
 

More from Sunil Yadav

Tree Leetcode - Interview Questions - Easy Collections
Tree Leetcode - Interview Questions - Easy CollectionsTree Leetcode - Interview Questions - Easy Collections
Tree Leetcode - Interview Questions - Easy CollectionsSunil Yadav
 
Leet Code May Coding Challenge - DataStructure and Algorithm Problems
Leet Code May Coding Challenge - DataStructure and Algorithm ProblemsLeet Code May Coding Challenge - DataStructure and Algorithm Problems
Leet Code May Coding Challenge - DataStructure and Algorithm ProblemsSunil Yadav
 
Bada Business, Dr. Vivek Bindra . Motivational Speaker (31 May)
Bada Business, Dr. Vivek Bindra . Motivational Speaker (31 May)Bada Business, Dr. Vivek Bindra . Motivational Speaker (31 May)
Bada Business, Dr. Vivek Bindra . Motivational Speaker (31 May)Sunil Yadav
 
Golang, Future of Programming Language.
Golang, Future of Programming Language.Golang, Future of Programming Language.
Golang, Future of Programming Language.Sunil Yadav
 
React Js Simplified
React Js SimplifiedReact Js Simplified
React Js SimplifiedSunil Yadav
 
LeetCode April Coding Challenge
LeetCode April Coding ChallengeLeetCode April Coding Challenge
LeetCode April Coding ChallengeSunil Yadav
 
Docker with Micro Service and WebServices
Docker with Micro Service and WebServicesDocker with Micro Service and WebServices
Docker with Micro Service and WebServicesSunil Yadav
 

More from Sunil Yadav (7)

Tree Leetcode - Interview Questions - Easy Collections
Tree Leetcode - Interview Questions - Easy CollectionsTree Leetcode - Interview Questions - Easy Collections
Tree Leetcode - Interview Questions - Easy Collections
 
Leet Code May Coding Challenge - DataStructure and Algorithm Problems
Leet Code May Coding Challenge - DataStructure and Algorithm ProblemsLeet Code May Coding Challenge - DataStructure and Algorithm Problems
Leet Code May Coding Challenge - DataStructure and Algorithm Problems
 
Bada Business, Dr. Vivek Bindra . Motivational Speaker (31 May)
Bada Business, Dr. Vivek Bindra . Motivational Speaker (31 May)Bada Business, Dr. Vivek Bindra . Motivational Speaker (31 May)
Bada Business, Dr. Vivek Bindra . Motivational Speaker (31 May)
 
Golang, Future of Programming Language.
Golang, Future of Programming Language.Golang, Future of Programming Language.
Golang, Future of Programming Language.
 
React Js Simplified
React Js SimplifiedReact Js Simplified
React Js Simplified
 
LeetCode April Coding Challenge
LeetCode April Coding ChallengeLeetCode April Coding Challenge
LeetCode April Coding Challenge
 
Docker with Micro Service and WebServices
Docker with Micro Service and WebServicesDocker with Micro Service and WebServices
Docker with Micro Service and WebServices
 

Recently uploaded

Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
 
costume and set research powerpoint presentation
costume and set research powerpoint presentationcostume and set research powerpoint presentation
costume and set research powerpoint presentationphoebematthew05
 
Science&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdfScience&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdfjimielynbastida
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraDeakin University
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptxLBM Solutions
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
Bluetooth Controlled Car with Arduino.pdf
Bluetooth Controlled Car with Arduino.pdfBluetooth Controlled Car with Arduino.pdf
Bluetooth Controlled Car with Arduino.pdfngoud9212
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 

Recently uploaded (20)

Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024
 
costume and set research powerpoint presentation
costume and set research powerpoint presentationcostume and set research powerpoint presentation
costume and set research powerpoint presentation
 
Science&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdfScience&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdf
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning era
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptx
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
Bluetooth Controlled Car with Arduino.pdf
Bluetooth Controlled Car with Arduino.pdfBluetooth Controlled Car with Arduino.pdf
Bluetooth Controlled Car with Arduino.pdf
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 

Linked List Leetcode - Easy Collections - Interview Questions Java

  • 2. Linked List problems are relatively easy to master. Do not forget the Two-pointer technique, which not only applicable to Array problems but also Linked List problems as well. Another technique to greatly simplify coding in linked list problems is the dummy node trick. We recommend: Reverse Linked List, Merge Two Sorted Lists and Linked List Cycle. For additional challenge, solve these problems recursively: Reverse Linked List, Palindrome Linked List and Merge Two Sorted Lists. IntroductION
  • 3. Delete Node in a Linked List Write a function to delete a node (except the tail) in a singly linked list, given only access to that node. Given linked list -- head = [4,5,1,9], which looks like following: Example 1: Input: head = [4,5,1,9], node = 5 Output: [4,1,9] Explanation: You are given the second node with value 5, the linked list should become 4 -> 1 -> 9 after calling your function. Example 2: Input: head = [4,5,1,9], node = 1 Output: [4,5,9] Explanation: You are given the third node with value 1, the linked list should become 4 -> 5 -> 9 after calling your function. Note: • The linked list will have at least two elements. • All of the nodes' values will be unique. • The given node will not be the tail and it will always be a valid node of the linked list. • Do not return anything from your function. /** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ class Solution { public void deleteNode(ListNode node) { ListNode Prev = null; while(node.next!=null){ node.val = node.next.val; Prev = node; node = node.next; } if(Prev!=null) Prev.next = null; } }
  • 4. Remove Nth Node From End of List Given a linked list, remove the n-th node from the end of list and return its head. Example: Given linked list: 1->2->3->4->5, and n = 2. After removing the second node from the end, the linked list becomes 1->2->3->5. Note: Given n will always be valid. Follow up: Could you do this in one pass? • /** * 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; } * } */ class Solution { public ListNode removeNthFromEnd(ListNode head, int n) { ListNode Prev = null; ListNode fN = head; ListNode slow = head; int counter = 1; while(head!=null){ if(counter>n){ Prev = slow; slow = slow.next; } counter++; head = head.next; } if(Prev!=null){ if(slow!=null) Prev.next = slow.next; else Prev.next = null; } if(Prev == null){ return fN.next; } return fN; } }
  • 5.  Reverse Linked List Reverse a singly linked list. Example: Input: 1->2->3->4->5->NULL Output: 5->4->3->2->1->NULL Follow up: A linked list can be reversed either iteratively or recursively. Could you implement both? • /** * 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; } * } */ class Solution { public ListNode reverseList(ListNode head) { ListNode root = head; ListNode Prev = null; while(head!=null){ ListNode nextNode = head.next; head.next = Prev; Prev = head; head = nextNode; } return Prev; } }
  • 6. Merge Two Sorted Lists Merge two sorted linked lists and return it as a new sorted list. The new list should be made by splicing together the nodes of the first two lists. Example: Input: 1->2->4, 1->3->4 Output: 1->1->2->3->4->4 /** * 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; } * } */ class Solution { public ListNode mergeTwoLists(ListNode l1, ListNode l2) { ListNode x = l1; ListNode y = l2; ListNode result = new ListNode(-1); ListNode fR = result; while(x!=null && y!=null){ if(x.val <= y.val){ result.next = new ListNode(x.val); x = x.next; }else{ result.next = new ListNode(y.val); y = y.next; } result = result.next; } if(x!=null){ result.next = x; result = result.next; } if(y!=null){ result.next = y; result = result.next; } return fR.next; }
  • 7. Palindrome Linked List Given a singly linked list, determine if it is a palindrome. Example 1: Input: 1->2 Output: false Example 2: Input: 1->2->2->1 Output: true Follow up:
 Could you do it in O(n) time and O(1) space? /** * 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; } * } */ class Solution { public boolean isPalindrome(ListNode head) { ListNode slow = head; ListNode fast = head; while(fast!=null && fast.next!=null){ slow = slow.next; fast = fast.next.next; } Stack<ListNode> stack = new Stack<>(); // Slow is at Middle Position while(slow!=null){ stack.push(slow); slow = slow.next; } while(!stack.isEmpty()){ if(head.val!=stack.pop().val){ return false; } head = head.next; } return true; } }
  • 8. Linked List Cycle Given a linked list, determine if it has a cycle in it. To represent a cycle in the given linked list, we use an integer pos which represents the position (0-indexed) in the linked list where tail connects to. If pos is -1, then there is no cycle in the linked list. Example 1: Input: head = [3,2,0,-4], pos = 1 Output: true Explanation: There is a cycle in the linked list, where tail connects to the second node. /** * Definition for singly-linked list. * class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */ public class Solution { public boolean hasCycle(ListNode head) { if(head == null){ return false; } ListNode slow = head; ListNode fast = head.next; while(true){ if(slow==null || fast==null){ return false; } if(slow==fast){ return true; } slow = slow.next; if(fast.next==null){ return false; } fast = fast.next.next; } } }