Problem
Problem:
Given a singly linked list and an integer constant k
, write a function to find the last element from the beginning whose position satisfies the condition ( n % k = 0 ), where n
is the number of elements in the list.
OR
Given a singly linked list, write a function to find the last element from the beginning whose n%k == 0, where n is the number of elements in the list and k is an integer constant. For example, if n = 19 and k = 3 then we should return 18th node.
Examples:
Example 1:
|
|
Example 2:
|
|
Example 3:
|
|
Solution
Method 1 - Iteration
-
Initialize Two Pointers and a Counter:
- Use a pointer to traverse the list and a counter to keep track of the positions.
- Maintain a
resultNode
to store the latest node that satisfies the condition ( n % k = 0 ).
-
Traverse the List:
- Iterate through the list, and for each node, check if the current position satisfies the condition ( n % k = 0 ).
- Update the
resultNode
whenever the condition is satisfied.
-
Return the Result:
- Return the
resultNode
, which holds the last node whose position satisfies the condition.
- Return the
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n)
, wheren
is the number of nodes in the linked list. The list is traversed once. - 🧺 Space complexity: aux space complexity is
O(1)
, since only a constant amount of extra space is used for the pointer.