We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Return Length of Arguments Passed

Number: 2820

Difficulty: Easy

Paid? No

Companies: Amazon, Google, Bloomberg


Problem Description

Write a function argumentsLength that returns the count of arguments passed to it. For example, argumentsLength(5) should return 1, and argumentsLength({}, null, "3") should return 3.


Key Insights

  • The challenge is to accept a variable number of arguments in the function.
  • Many languages offer built-in mechanisms (e.g., rest parameters in JavaScript, *args in Python, varargs in Java) to handle an arbitrary number of arguments.
  • The task is essentially to count the elements in the collection of passed arguments.

Space and Time Complexity

Time Complexity: O(1), as the operation involves simply returning the number of arguments. Space Complexity: O(1), since no additional space is needed.


Solution

The solution involves defining a function that can handle a variable number of arguments using language-specific features. In Python, you can use *args to receive all arguments as a tuple, and then return its length. In JavaScript, rest parameters (...) can be used to collect arguments into an array and check its length. C++ offers parameter packs, and by using sizeof... on the parameter pack, you can obtain the argument count. In Java, you can use varargs which treats the additional arguments as an array and then return its length. This approach leverages built-in language features to make counting the passed arguments straightforward.


Code Solutions

# Define a function using *args to accept a variable number of arguments
def argumentsLength(*args):
    # Return the count of arguments by using the len() function on the tuple of arguments
    return len(args)

# Example usage:
print(argumentsLength(5))          # Output: 1
print(argumentsLength({}, None, "3"))  # Output: 3
← Back to All Questions