#6 Daily Problems -RemoveKFromList

Arun Pandian M
2 min readJul 24, 2020

--

Hi friends, This is my 6th day of solving one problem per day. I have started to solve the linked list related problems. Actually it is very interesting and fun to solve this type of problems.

Problem:

Note: Try to solve this task in O(n) time using O(1) additional space, where n is the number of elements in the list, since this is what you'll be asked to do during an interview.

Given a singly linked list of integers l and an integer k, remove all elements from list l that have a value equal to k.

Example

  • For l = [3, 1, 2, 3, 4, 5] and k = 3, the output should be
    removeKFromList(l, k) = [1, 2, 4, 5];
  • For l = [1, 2, 3, 4, 5, 6, 7] and k = 10, the output should be
    removeKFromList(l, k) = [1, 2, 3, 4, 5, 6, 7].

Input/Output

  • [execution time limit] 3 seconds (java)
  • [input] linkedlist.integer l
  • A singly linked list of integers.
  • Guaranteed constraints:
    0 ≤ list size ≤ 105,
    -1000 ≤ element value ≤ 1000.
  • [input] integer k
  • An integer.
  • Guaranteed constraints:
    -1000 ≤ k ≤ 1000.
  • [output] linkedlist.integer
  • Return l with all the values equal to k removed.

My solution:

// Singly-linked lists are already defined with this interface:// class ListNode<T> {//   ListNode(T x) {//     value = x;//   }//   T value;//   ListNode<T> next;// }//public ListNode<Integer> removeKFromList(ListNode<Integer> l, int k) {
ListNode temp = l;

// if give linked list is empty then return
if (l == null){
return l;
}

// iterate until given starting value are matching
while(l.value == k ){
l = l.next;
if (l == null)
return l; // return, after the matching values and removed the remains are null
}

// check the next values are matching if matched then remove the elements from the linked list
while(temp.next != null){
if (temp.next.value.equals(k)){
temp.next = temp.next.next;
}else{
temp=temp.next;
}
}
return l;
}

Ok friends, please help me to improve this solution ad help me to learn somethings from you. Thanks. lets meet tomorrow.

Happy coding!

Buy me a coffee?
If you like this article, you can buy me a coffee. Thanks!

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Arun Pandian M
Arun Pandian M

Written by Arun Pandian M

Senior Android developer at FundsIndia, A time investor to learn new things about Programming. Currently in a relationship with Green Bug(Android).

No responses yet

Write a response