Add K Nodes Problem Statement

You are given a singly linked list of integers and an integer 'K'. Your task is to modify the linked list by inserting a new node after every 'K' node in the linked list. The value of the new node should be the sum of the previous 'K' nodes.

Note:

If the number of nodes remaining in the linked list is less than 'K' but greater than zero, insert a node with the value equal to the sum of the remaining nodes.

Input:

Element list: a sequence of integers followed by -1, signifying the end (e.g., 1 2 3 -1)
K: an integer indicating the number of nodes to consider

Output:

Modified linked list: elements space-separated and terminated by -1 (e.g., 1 2 3 6 -1)

Example:

Input:
1 2 3 4 5 -1
K = 2
Output:
1 2 3 4 7 5 5 -1

Constraints:

  • 0 ≤ L <= 5*105 where 'L' is the number of nodes in the linked list.
  • -103 ≤ data ≤ 103 and data is not equal to -1.
  • 1 ≤ K ≤ 106
  • Time Limit: 1 sec
Be the first one to answer
Add answer anonymously...
Micron Technology Associate Software Engineer Interview Questions
Stay ahead in your career. Get AmbitionBox app
qr-code
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+

Reviews

4 L+

Interviews

4 Cr+

Salaries

1 Cr+

Users/Month

Contribute to help millions

Made with ❤️ in India. Trademarks belong to their respective owners. All rights reserved © 2024 Info Edge (India) Ltd.

Follow us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter