Back to blog
Feb 27, 2025
4 min read

Return Length of Arguments Passed

Write a function that returns the number of arguments passed to it.

Difficulty: Easy | Acceptance: 94.50% | Paid: No Topics: N/A

Write a function argumentsLength that returns the number of arguments passed to it. The function should accept any number of arguments of any type and return the count of arguments.

Examples

Example 1

Input:

args = [5]

Output:

1

Explanation: argumentsLength(5); // 1

One value was passed to the function so it should return 1.

Example 2

Input:

args = [{}, null, "3"]

Output:

3

Explanation: argumentsLength(, null, “3”); // 3

Three values were passed to the function so it should return 3.

Constraints

0 <= args.length <= 100

Using Built-in Length Property

Intuition Most programming languages provide a built-in property or operator to get the length of a collection or variadic arguments, which is the most efficient way to solve this problem.

Steps

  • Use the language’s built-in length/size property to get the number of arguments
  • Return the length
python
def argumentsLength(*args) -> int:
    return len(args)

Complexity

  • Time: O(1)
  • Space: O(1)
  • Notes: This is the most efficient approach as it directly accesses the length property without any additional computation.

Manual Counting with Loop

Intuition We can manually count the number of arguments by iterating through them and incrementing a counter for each argument.

Steps

  • Initialize a counter to 0
  • Iterate through each argument
  • Increment the counter for each argument
  • Return the counter
python
def argumentsLength(*args) -> int:
    count = 0
    for _ in args:
        count += 1
    return count

Complexity

  • Time: O(n)
  • Space: O(1)
  • Notes: This approach is less efficient than using the built-in length property but demonstrates the underlying concept of counting.

Using Array/List Conversion

Intuition We can convert the arguments to an array or list and then use the length/size property of the collection to get the count.

Steps

  • Convert the arguments to an array or list
  • Use the length/size property of the collection
  • Return the length
python
def argumentsLength(*args) -> int:
    return len(list(args))

Complexity

  • Time: O(n)
  • Space: O(n)
  • Notes: This approach creates an additional data structure, which uses extra space. It’s less efficient than the built-in length property approach.