Bird
Raised Fist0
Interview Preplinked-list-advancedeasyAmazonGoogle

Convert Binary Number in Linked List to Integer

Choose your preparation mode4 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
📋
Problem

Imagine you receive a linked list representing a binary number from a hardware sensor, and you need to convert it into a decimal integer to process it further.

Given head which is a reference node to a singly-linked list. The value of each node in the linked list is either 0 or 1. The linked list holds the binary representation of a number. Return the decimal value of the number in the linked list.

The number of nodes in the linked list is in the range [1, 10^5].Each node's value is either 0 or 1.
Edge cases: Single node with value 0 → output 0Single node with value 1 → output 1All nodes are 0 → output 0
</>
IDE
def getDecimalValue(head: ListNode) -> int:public int getDecimalValue(ListNode head)int getDecimalValue(ListNode* head)function getDecimalValue(head)
def getDecimalValue(head):
    # Write your solution here
    pass
class Solution {
    public int getDecimalValue(ListNode head) {
        // Write your solution here
        return 0;
    }
}
#include <vector>
using namespace std;

int getDecimalValue(ListNode* head) {
    // Write your solution here
    return 0;
}
function getDecimalValue(head) {
    // Write your solution here
}
Coming soon
0/9
Common Bugs to Avoid
Wrong: 0Returning 0 for all inputs due to uninitialized or reset accumulator.Initialize result = 0 before loop and update with result = (result << 1) | node.val inside loop.
Wrong: Wrong decimal due to off-by-one bit shiftShifting bits after adding current node value instead of before.Shift result left first, then OR with current bit: result = (result << 1) | node.val.
Wrong: Wrong decimal due to skipping nodesGreedy approach that skips some bits or processes only some nodes.Process every node in order without skipping to accumulate bits correctly.
Wrong: TLE or timeoutUsing string concatenation or recursion without memoization causing O(n^2) or worse.Use iterative bit shift accumulation in O(n) time.
Test Cases
t1_01basic
Input{"head":[1,0,1]}
Expected5

The binary number is 101 which equals 5 in decimal.

t1_02basic
Input{"head":[1,1,0,1]}
Expected13

Binary 1101 equals decimal 13.

t2_01edge
Input{"head":[0]}
Expected0

Single node with value 0 should return 0.

t2_02edge
Input{"head":[1]}
Expected1

Single node with value 1 should return 1.

t2_03edge
Input{"head":[0,0,0,0]}
Expected0

All nodes zero should return 0 regardless of length.

t3_01corner
Input{"head":[1,0,1,0,1,0,1]}
Expected85

Binary 1010101 equals decimal 85.

t3_02corner
Input{"head":[1,1,1,1,1]}
Expected31

All ones for 5 bits equals 2^5 - 1 = 31.

t3_03corner
Input{"head":[1,0,0,1,1]}
Expected19

Binary 10011 equals decimal 19.

t4_01performance
Input{"head":[1,0,1,1,0,1,0,1,1,0,1,0,1,1,0,1,0,1,1,0,1,0,1,1,0,1,0,1,1,0,1,0,1,1,0,1,0,1,1,0,1,0,1,1,0,1,0,1,1,0,1,0,1,1,0,1,0,1,1,0,1,0,1,1,0,1,0,1,1,0,1,0,1,1,0,1,0,1,1,0,1,0,1,1,0,1,0,1,1,0,1,0,1,1,0]}
⏱ Performance - must finish in 2000ms

Large input with n=100 nodes to test O(n) time complexity within 2 seconds.

Practice

(1/5)
1. Consider the following Python code implementing browser history with two stacks. After executing the sequence of operations below, what is the output of the last back call?
browserHistory = BrowserHistory("leetcode.com")
browserHistory.visit("google.com")
browserHistory.visit("facebook.com")
browserHistory.visit("youtube.com")
print(browserHistory.back(1))
print(browserHistory.back(1))
print(browserHistory.forward(1))
easy
A. "youtube.com"
B. "google.com"
C. "facebook.com"
D. "leetcode.com"

Solution

  1. Step 1: Trace back(1) after visiting youtube.com

    back_stack = ["leetcode.com", "google.com", "facebook.com", "youtube.com"] Pop "youtube.com" to forward_stack, back_stack top is "facebook.com".
  2. Step 2: Trace back(1) again and forward(1)

    Second back(1): pop "facebook.com" to forward_stack, top is "google.com". Forward(1): pop "facebook.com" from forward_stack back to back_stack, top is "facebook.com".
  3. Final Answer:

    Option C -> Option C
  4. Quick Check:

    Last forward returns "facebook.com" as expected [OK]
Hint: Back and forward operations move URLs between stacks correctly [OK]
Common Mistakes:
  • Off-by-one errors in popping stacks
  • Confusing forward and back stacks
  • Returning wrong top element after operations
2. What is the time complexity of the addAtTail operation in the optimal linked list implementation that maintains a tail pointer and size variable?
medium
A. O(n), because traversal is needed to find the tail
B. O(log n), because the list is balanced using sentinel nodes
C. O(1), because the tail pointer allows direct access to the last node
D. O(n), because updating the size requires traversal

Solution

  1. Step 1: Identify operation steps

    addAtTail uses the tail pointer to append a new node directly without traversal.
  2. Step 2: Analyze complexity

    Since tail pointer gives direct access, adding at tail is O(1). Size update is O(1) as it's a simple increment.
  3. Final Answer:

    Option C -> Option C
  4. Quick Check:

    Tail pointer eliminates traversal, so addAtTail is constant time [OK]
Hint: Tail pointer enables O(1) tail insertions [OK]
Common Mistakes:
  • Assuming traversal needed to find tail
  • Confusing size update cost
  • Thinking sentinel nodes balance list
3. Examine the following buggy code snippet from an optimal linked list implementation. Which line contains the subtle bug that can cause the tail pointer to point to a deleted node after a deletion at the tail?
medium
A. Line 8: self.tail = prev
B. Line 6: prev.next = prev.next.next
C. Line 3: if index < 0 or index >= self.size:
D. Line 7: if index == self.size - 1:

Solution

  1. Step 1: Understand tail update condition

    The tail pointer should update when deleting the last node, which is at index size-1 before deletion.
  2. Step 2: Identify bug

    At line 8, the tail pointer is set to prev, but prev may not be the correct new tail if the deleted node was the last node. The tail pointer should be updated after size decrement and possibly set to the correct node.
  3. Step 3: Correct fix

    Update tail pointer after size decrement and ensure it points to the last node in the list.
  4. Final Answer:

    Option A -> Option A
  5. Quick Check:

    Tail pointer update must correctly reflect the new last node after deletion [OK]
Hint: Tail pointer update must be done carefully after deletion [OK]
Common Mistakes:
  • Updating tail before size decrement
  • Not updating tail on last node deletion
  • Incorrect traversal to prev node
4. What is the time and space complexity of the optimal in-place partition algorithm for a linked list of length n around value x?
medium
A. Time: O(n), Space: O(1)
B. Time: O(n), Space: O(n)
C. Time: O(n^2), Space: O(1)
D. Time: O(n log n), Space: O(1)

Solution

  1. Step 1: Identify complexity of outer and inner loops

    The algorithm traverses the list once, performing constant-time pointer operations per node, so time is O(n).
  2. Step 2: Check if recursion stack adds extra space

    No recursion or extra data structures are used; only a few pointers are maintained, so space is O(1).
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Single pass with constant pointers -> O(n) time and O(1) space [OK]
Hint: Single pass with pointer updates -> O(n) time, O(1) space [OK]
Common Mistakes:
  • Confusing with sorting complexity O(n log n)
  • Assuming extra arrays cause O(n) space
  • Mistaking pointer updates as nested loops causing O(n^2)
5. What is the time complexity of the optimal in-place split algorithm for splitting a linked list of length n into k parts, and why?
medium
A. O(n) because splitting is done in a single pass without extra overhead.
B. O(n * k) because for each part, we traverse nodes up to part size.
C. O(n + k) because we first count nodes in one pass, then split in one pass plus overhead for k parts.
D. O(k) because the algorithm mainly depends on the number of parts.

Solution

  1. Step 1: Identify passes over the list

    One pass to count total nodes (O(n)), one pass to split nodes into k parts (O(n)).
  2. Step 2: Account for overhead

    Creating dummy heads and managing k parts adds O(k) overhead, but does not dominate.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Two passes over n plus O(k) overhead is O(n), since k ≤ n [OK]
Hint: Counting + splitting passes plus k overhead -> O(n) [OK]
Common Mistakes:
  • Assuming nested loops cause O(n*k)
  • Ignoring overhead of dummy heads
  • Confusing single pass with O(n) ignoring k