First Digit Sum

🎯 Linked List Hurdle

First Digit Sum

Difficulty: ⚫◯◯◯

Tags: linked-list, digit-sum, search

Hurdle: Passing this question is sufficient to pass the linked lists hurdle.

Description

Write a function first_digit_sum that takes two arguments:

  • head: a pointer to the first node of a linked list
  • target: an integer representing the target digit sum

The function should return the first value in the linked list whose digit sum equals target.

If no such value exists, return -1.

What is a "digit sum"?

The digit sum of a number is the sum of all its digits:

  • digit_sum(123) = 1 + 2 + 3 = 6
  • digit_sum(45) = 4 + 5 = 9
  • digit_sum(7) = 7
  • digit_sum(100) = 1 + 0 + 0 = 1

For negative numbers, use the absolute value:

  • digit_sum(-123) = 1 + 2 + 3 = 6

Examples

Example 1: Found at First Node

List: 23 -> 14 -> 32 -> 5 -> X, target = 5

23: 2+3=5 ✓ (matches!)

Output: 23

Example 2: Not Found

List: 99 -> 88 -> 77 -> X, target = 5

99: 9+9=18 ✗
88: 8+8=16 ✗
77: 7+7=14 ✗

Output: -1

Example 3: Found in Middle

List: 11 -> 22 -> 33 -> X, target = 6

11: 1+1=2 ✗
22: 2+2=4 ✗
33: 3+3=6 ✓

Output: 33

Example 4: Multiple Matches (Return First)

List: 123 -> 456 -> 16 -> X, target = 7

123: 1+2+3=6 ✗
456: 4+5+6=15 ✗
16: 1+6=7 ✓

Output: 16

Example 5: Zeros in Number

List: 100 -> 200 -> 300 -> X, target = 1

100: 1+0+0=1 ✓

Output: 100

Example 6: Empty List

List: (empty), target = 5

Output: -1

Function Signature

int first_digit_sum(struct node *head, int target);

Data Structure

struct node {
    struct node *next;
    int          data;
};

Constraints

  • You can assume target is a positive integer (1 or greater).
  • The list may be empty (return -1).
  • For negative numbers in the list, calculate digit sum of the absolute value.
  • Return only a single integer.
  • Do not change the linked list.
  • Do not use arrays.
  • Do not call malloc.
  • Do not call scanf, getchar, or fgets.
  • Do not call printf.

Hints

  • Create a helper function to calculate the digit sum of a number.
  • Use % 10 to get the last digit, and / 10 to remove it.
  • Handle negative numbers by using absolute value (or just make it positive).
  • Return immediately when you find the first match.

Testing

The first argument is the target, remaining arguments form the linked list.

./first-digit-sum 5 23 14 32 5
23

./first-digit-sum 5 99 88 77
-1

./first-digit-sum 6 11 22 33
33

./first-digit-sum 7 123 456 16
16

./first-digit-sum 1 100 200 300
100

./first-digit-sum 10 19 28 37
19

./first-digit-sum 5
-1
Code Editor
Output
Run your code to see output here...