Resolve Calls Against Fixed and Variadic Signatures

Medium · Coding & Algorithms · Software Engineer · Onsite

Problem Statement

Implement a signature-resolution engine for a function registry containing both fixed-arity and variadic declarations:

def find_matching_functions(
    names: list[str],
    param_types: list[list[str]],
    is_variadic: list[bool],
    queries: list[list[str]],
) -> list[list[str]]:

Three equal-length parallel lists define the registered declarations: entry i has unique identifier names[i], ordered parameter type list param_types[i], and boolean flag is_variadic[i]. Given queries, where each element represents the ordered argument types passed at a call site, return one list per query containing every function name that accepts that argument sequence.

Apply these exact matching and ordering rules:

  • Fixed-arity (is_variadic[i] == False): accepts query q if and only if len(q) == len(param_types[i]) and q[j] == param_types[i][j] at every index j.
  • Variadic (is_variadic[i] == True, with m = len(param_types[i]) >= 1): accepts query q if and only if len(q) >= m, every fixed leading slot 0 <= j < m - 1 satisfies q[j] == param_types[i][j], and every trailing slot m - 1 <= j < len(q) equals param_types[i][m - 1]. In particular, the variadic final parameter must be supplied at least once (zero repetitions never match).
  • Exact type equality: compare type names as case-sensitive strings with no implicit conversions or subtyping.
  • Deterministic output: sort each query's matching function names in ascending standard string order (sorted(...)), using [] when no declaration matches, and preserve query order across the outer result list.

Examples

Example 1

Input:
  names       = ["boot", "blend", "plot", "route", "total"]
  param_types = [[], ["float", "float"], ["str", "int", "float"], ["str"], ["float"]]
  is_variadic = [False, False, True, True, True]
  queries     = [
      [],
      ["float", "float"],
      ["str", "int", "float", "float"],
      ["str", "int"],
      ["str", "str", "str"],
      ["int"],
  ]

Output:
  [["boot"], ["blend", "total"], ["plot"], [], ["route"], []]

Walk-through: - [] matches boot (zero-parameter fixed function); variadic functions always require at least one argument. - ["float", "float"] matches blend via exact match and total via "float" repeated twice. - ["str", "int", "float", "float"] matches plot ("str", "int", followed by two "float" arguments). - ["str", "int"] is too short for plot (needs at least 3 arguments) and fails route at index 1, returning []. - ["str", "str", "str"] matches route ("str" repeated three times). - ["int"] matches nothing.

Example 2

Input:
  names       = ["Send", "send", "sendMany", "sendTagged"]
  param_types = [["bytes"], ["bytes", "bytes"], ["bytes"], ["int", "bytes"]]
  is_variadic = [False, False, True, True]
  queries     = [
      ["bytes"],
      ["bytes", "bytes"],
      ["int", "bytes", "bytes"],
      ["int"],
  ]

Output:
  [["Send", "sendMany"], ["send", "sendMany"], ["sendTagged"], []]

Walk-through: - ["bytes"] matches fixed Send and variadic sendMany (one "bytes" occurrence); uppercase "Send" precedes lowercase "sendMany" under ASCII sort order. - ["bytes", "bytes"] matches fixed send and variadic sendMany (two "bytes" occurrences). - ["int", "bytes", "bytes"] matches sendTagged, whereas ["int"] omits its required "bytes" tail and returns [].

Constraints

  • 1 <= len(names) <= 10^4 and len(param_types) == len(is_variadic) == len(names)
  • Every name in names is distinct, has length 1 to 30, and consists of A-Z, a-z, 0-9, and _.
  • 0 <= len(param_types[i]) <= 20, with len(param_types[i]) >= 1 whenever is_variadic[i] is True.
  • Every type name has length 1 to 20 and consists of A-Z, a-z, 0-9, and _.
  • 1 <= len(queries) <= 10^4, 0 <= len(queries[j]) <= 100, and the sum of len(q) over all queries is at most 2 * 10^5.
  • Across all queries combined, at most 10^6 function names appear in the returned output.

Step-by-step walkthrough

  1. Understand exact vs. variadic matching

    We receive a registry of callable declarations — each given by names[i], its parameter type sequence param_types[i], and a boolean flag is_variadic[i] — together with a list of call-site queries. For every query q, we must return all matching function names sorted in standard ascending string order.

    Compare the two matching rules carefully:

    • Non-variadic (is_variadic == False): Matches q if and only if q == param_types[i] (identical length and identical case-sensitive type at every index).
    • Variadic (is_variadic == True, with m = len(param_types[i]) >= 1): Leading slots 0 .. m - 2 match q index-for-index, while the trailing type param_types[i][m - 1] repeats one or more times across the rest of q (len(q) >= m).
    Query q = ["str", "int", "float", "float"]
      plot(str, int, float...)   -> MATCHES ("str", "int", then "float" repeated 2 times)
      route(str...)              -> NO      (remaining args after index 0 are not "str")
    
    Query q = ["str", "int"]
      plot(str, int, float...)   -> NO      (final "float..." must appear AT LEAST ONCE, never 0 times!)
    
    Query q = []
      boot()  [non-variadic]     -> MATCHES
      any variadic function      -> NO      (every variadic function needs at least 1 argument)
    
  2. Why checking every function per query is too slow

    The direct brute-force approach checks every function against every query one by one:

    def brute_accepts(params: list[str], variadic: bool, query: list[str]) -> bool:
        m = len(params)
        if not variadic:
            return query == params
        if len(query) < m:
            return False
        for j in range(len(query)):
            expected = params[j] if j < m - 1 else params[m - 1]
            if query[j] != expected:
                return False
        return True
    

    With up to F = 10^4 functions and Q = 10^4 queries, nested loops perform F * Q = 10^8 function checks, each scanning up to 100 argument types. That is billions of operations in Python. Instead of scanning all F functions per query, we want to index the library once and look up only the signatures that could match q.

  3. Key insight: every matching variadic signature is a prefix of the query

    Suppose a variadic function with parameter list p of length m accepts a non-empty query q. What must p look like?

    1. Its fixed leading parameters p[0 .. m - 2] equal q[0 .. m - 2].
    2. Its variadic parameter p[m - 1] equals q[m - 1] (the very first repeated slot), and also equals q[m], q[m + 1], ..., q[len(q) - 1].

    Putting (1) and the first part of (2) together gives a huge simplification: p must equal q[:m], the length-m prefix of q!

    And which prefix lengths m satisfy the second part of (2) (that q[m - 1 :] is all one identical type)? Let run_start be the earliest index where the trailing streak of identical types at the end of q begins. Then q[m - 1 :] is all one type if and only if m - 1 >= run_start, which rearranges to m >= run_start + 1:

    Query q = [ "a",  "b",  "b",  "b" ]    (len = 4)
      indices:   0     1     2     3
                       ^-----------^
                       trailing streak of "b" starts at run_start = 1
    
    Valid variadic lengths m (from run_start + 1 = 2 up to len(q) = 4):
      m = 2 -> prefix ("a", "b")          (1 fixed "a", then "b" x 3)  MATCHES!
      m = 3 -> prefix ("a", "b", "b")     (fixed "a","b", then "b" x 2) MATCHES!
      m = 4 -> prefix ("a", "b", "b", "b")(fixed "a","b","b", then "b" x 1) MATCHES!
      (m = 1 -> prefix ("a",) is excluded because q[0:] = ["a","b","b","b"] is NOT all one type)
    

    Notice too that signature lengths in the library are at most 20 (longest_variadic <= 20). So even on a 100-element query, we check at most 20 prefixes!

  4. Index the function library by parameter tuple

    We build two hash maps before answering any queries:

    • exact_index: maps tuple(param_types[i]) -> [function names] for non-variadic functions.
    • variadic_index: maps tuple(param_types[i]) -> [function names] for variadic functions.

    Why convert param_types[i] to a tuple instead of joining strings like "".join(param_types[i])? Python lists cannot be dictionary keys because they are mutable, whereas tuples of strings are hashable and preserve boundaries cleanly (("ab", "c") and ("a", "bc") never collide the way "abc" would!). Because multiple functions can share the exact same signature, each tuple maps to a list of names.

    from typing import Dict, List, Tuple
    
    
    def add_to_index(
        index: Dict[Tuple[str, ...], List[str]], key: Tuple[str, ...], name: str
    ) -> None:
        """Append `name` under signature tuple `key` in `index`."""
        if key not in index:
            index[key] = []
        index[key].append(name)
    
  5. Find where the trailing streak of identical types begins

    For any non-empty query q, start a pointer start at the last index len(q) - 1 and step leftward as long as the element to the left (q[start - 1]) matches q[-1]:

    q = ["str", "int", "float", "float"]
      start = 3 ("float"): q[2] == "float" -> decrement to 2
      start = 2 ("float"): q[1] == "int" != "float" -> stop! return 2
    
    def last_run_start(query: list[str]) -> int:
        """Return the first index of the trailing run of identical types (query is non-empty).
    
        Example: ["a", "b", "b", "b"] -> 1 because indices 1..3 are all "b".
        """
        start = len(query) - 1
        while start > 0 and query[start - 1] == query[-1]:
            start -= 1
        return start
    
  6. Answer each query and trace Example 1

    For each query:

    1. Convert query to query_key = tuple(query) once.
    2. Copy any exact matches via matches = list(exact_index.get(query_key, [])). Making a fresh list(...) copy is essential — otherwise matches.extend(...) and matches.sort() would mutate the list stored inside exact_index and corrupt later queries!
    3. If query is non-empty, compute first_m = last_run_start(query) + 1 and last_m = min(len(query), longest_variadic), and append variadic_index.get(query_key[:m], []) for each m in range(first_m, last_m + 1). Every m has a distinct tuple length, so no function can ever be added twice.
    4. Sort matches and append to results.
    Example 1 trace:
      exact_index    = {(): ["boot"], ("float", "float"): ["blend"]}
      variadic_index = {("str", "int", "float"): ["plot"], ("str",): ["route"], ("float",): ["total"]}
      longest_variadic = 3
    
      1. q = []:
         exact -> ["boot"]; `if query:` skipped -> ["boot"]
      2. q = ["float", "float"]:
         exact -> ["blend"]; run_start = 0 -> m in 1..min(2, 3)=2:
           m=1 ("float",) -> ["total"]; m=2 ("float", "float") -> []
         sorted -> ["blend", "total"]
      3. q = ["str", "int", "float", "float"]:
         exact -> []; run_start = 2 -> m in 3..min(4, 3)=3:
           m=3 ("str", "int", "float") -> ["plot"]
         sorted -> ["plot"]
      4. q = ["str", "int"]:
         exact -> []; run_start = 1 -> m in 2..min(2, 3)=2:
           m=2 ("str", "int") -> []
         sorted -> []
    
  7. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    
    
    def add_to_index(
        index: Dict[Tuple[str, ...], List[str]], key: Tuple[str, ...], name: str
    ) -> None:
        """Append `name` under signature tuple `key` in `index`."""
        if key not in index:
            index[key] = []
        index[key].append(name)
    
    
    def last_run_start(query: list[str]) -> int:
        """Return the first index of the trailing run of identical types (query is non-empty).
    
        Example: ["a", "b", "b", "b"] -> 1 because indices 1..3 are all "b".
        """
        start = len(query) - 1
        while start > 0 and query[start - 1] == query[-1]:
            start -= 1
        return start
    
    
    def find_matching_functions(
        names: list[str],
        param_types: list[list[str]],
        is_variadic: list[bool],
        queries: list[list[str]],
    ) -> list[list[str]]:
        # exact_index:    {tuple(params): [non_variadic_fn_names]}
        # variadic_index: {tuple(params): [variadic_fn_names]}
        # Using tuples of strings avoids both unhashable lists and string-join collisions.
        exact_index: Dict[Tuple[str, ...], List[str]] = {}
        variadic_index: Dict[Tuple[str, ...], List[str]] = {}
        longest_variadic = 0
    
        # Phase 1: index every function signature once by its parameter tuple.
        for i in range(len(names)):
            sig_key = tuple(param_types[i])
            if is_variadic[i]:
                add_to_index(variadic_index, sig_key, names[i])
                longest_variadic = max(longest_variadic, len(sig_key))
            else:
                add_to_index(exact_index, sig_key, names[i])
    
        # Phase 2: resolve each query via O(1) exact lookup + at most `longest_variadic` prefix lookups.
        results: list[list[str]] = []
        for query in queries:
            query_key = tuple(query)
            # Copy the list with `list(...)` so `.extend()` and `.sort()` never mutate `exact_index`.
            matches = list(exact_index.get(query_key, []))
    
            # Variadic functions require >= 1 argument for their final parameter, so `[]` cannot match any.
            if query:
                # A variadic signature `p` of length `m` matches `query` iff:
                #   1) `p == query[:m]` (its m parameters equal the first m query types), and
                #   2) `query[m - 1:]` is all one repeated type, i.e. `m - 1 >= run_start`.
                run_start = last_run_start(query)
                first_m = run_start + 1
                last_m = min(len(query), longest_variadic)
                for m in range(first_m, last_m + 1):
                    prefix_key = query_key[:m]
                    matches.extend(variadic_index.get(prefix_key, []))
    
            matches.sort()
            results.append(matches)
        return results
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Think of the function library as two filing cabinets of function blueprints keyed by their parameter-type tuple: one cabinet for fixed-arity functions (functions taking an exact number of arguments) and a second cabinet for variadic functions (functions whose final parameter repeats one or more times, like plot(str, int, float...)). Instead of pulling out all 10,000 blueprints for every call, we inspect the call's argument list and directly pull the tiny handful of drawer labels that could match!

Checking every function against every query naively performs F * Q = 10,000 * 10,000 = 100,000,000 signature comparisons, which is far too slow. By noticing that any variadic signature of length m matching a query q must equal the prefix q[:m] and have a single repeated type across q[m - 1:], we invert the search: we find the trailing run (the unbroken streak of identical types at the very end of q) and probe at most longest_variadic <= 20 prefixes in O(1) dictionary lookups!

Walk through q = ["a", "b", "b", "b"] against a library containing non-variadic exact(a, b, b, b) and variadic a1(a...), ab(a, b...), abb(a, b, b...), and abbb(a, b, b, b...):

  1. Exact lookup: Check exact_index[("a", "b", "b", "b")] -> finds "exact".
  2. Find the trailing run: Walking left from index 3 ("b"), indices 1, 2, 3 are all "b", while index 0 is "a", so run_start = 1.
  3. Probe valid variadic prefix lengths m from run_start + 1 = 2 to 4:
    • m = 2: ("a", "b") -> finds "ab" ("b" repeated 3 times).
    • m = 3: ("a", "b", "b") -> finds "abb" ("b" repeated 2 times).
    • m = 4: ("a", "b", "b", "b") -> finds "abbb" ("b" repeated 1 time).
    • Notice m = 1 (("a",) for a1) is skipped automatically because 1 < run_start + 1, reflecting that "a" cannot repeat across "b"s.
  4. Sort names: Plain ASCII / lexicographic sort (comparing characters by Unicode code point, the default in Python's .sort()) returns ["ab", "abb", "abbb", "exact"].

Complexity

Let S be the total number of parameter types across all F functions in the library, L be the length of a single query, K be the maximum variadic signature length (K <= 20 in the constraints), and R be the number of matching function names returned for that query.

  • Time to build indexes: O(S) average time. We loop over the F functions once, converting each parameter list into a hashable key (an immutable tuple that Python can hash into a dictionary) and appending its name in O(1) average time per function.
  • Time per query: O(L + min(L, K)^2 + R log R) average time. Converting query to a tuple and scanning its trailing run both take O(L) steps. Next, slicing and hashing prefixes query_key[:m] for m up to min(L, K) touches at most 1 + 2 + ... + K = K * (K + 1) / 2 elements (<= 210 string references since K <= 20, independent of F!). Finally, sorting the R matched names takes O(R log R) string comparisons. Across all Q queries, total work is linear in the library size and query input plus O(Q * K^2) and output sorting.
  • Space: O(S) auxiliary space (excluding the returned output list) to store the two signature-tuple dictionaries.

Edge cases

  • Empty query []: Matches non-variadic zero-parameter functions (param_types[i] == []) and never matches any variadic function because the variadic parameter must appear at least once.
  • Multiple functions with identical signatures: Storing a list of names per tuple key returns all of them, and .sort() orders them deterministically.
  • Same parameter list present as both variadic and non-variadic: For example Send(bytes) and sendMany(bytes...) both match ["bytes"] without colliding because exact_index and variadic_index are separate dictionaries.
  • Long query whose trailing run starts past index 20 (for example 25 "x"s followed by 3 "y"s): first_m = 26 > last_m <= 20, so range(first_m, last_m + 1) is empty and finishes in zero variadic lookups.
  • Case sensitivity and ASCII ordering: "Int" and "int" are distinct types, and Python's .sort() orders '0'..'9' before 'A'..'Z', then '_', then 'a'..'z'.

Common mistakes

  • Allowing a variadic parameter to repeat zero times: Unlike some programming languages, this specification requires len(q) >= m (one or more repetitions), so plot(str, int, float...) must not match ["str", "int"].
  • Probing only one variadic prefix length: Checking only m = run_start + 1 or only m = len(q) misses valid signatures like abb(a, b, b...) on ["a", "b", "b", "b"].
  • Mutating the list stored inside exact_index: Writing matches = exact_index.get(query_key, []) without wrapping in list(...) causes matches.extend(...) to permanently append variadic functions into exact_index, corrupting subsequent identical queries!
  • Joining type names without a safe delimiter ("".join(params)): Collides ["int", "s"] with ["i", "nts"]; using tuple(params) avoids string-concatenation collisions altogether.
  • Calling last_run_start on an empty query []: Guard with if query: first so len(query) - 1 never indexes -1 on an empty list.

Alternative approaches

  • Trie of variadic signatures: A trie (a prefix tree where each edge is one parameter type) lets you walk query down one step at a time from m = 1 to min(L, K) and collect variadic functions at every depth m >= run_start + 1. That trims the variadic lookup cost from O(min(L, K)^2) tuple slicing to O(min(L, K)), which pays off if K could be thousands rather than 20.
  • Memoizing repeated queries: If real call-site workloads repeat the exact same tuple(query) thousands of times, caching query_key -> sorted_matches answers duplicates in O(L) without re-sorting.

Follow-up questions

  • How would you return only the single most specific overload instead of every matching function? Define a strict specificity ranking just as compilers do: first prefer an exact non-variadic match over any variadic match (matching Java's overload resolution rules); if only variadic functions match, prefer the candidate with the largest m (the longest fixed prefix before falling back to repetition). If two functions still tie at that winning rank, raise an AmbiguousCallError rather than picking arbitrarily.
  • What changes if types form an inheritance hierarchy (subtyping), such as Dog matching Animal? Direct tuple hashing no longer works because one argument type Dog can match Dog, Mammal, or Animal. Instead, store signatures in a trie keyed by parameter type and traverse it via DFS/backtracking: at argument position j, branch across edges for query[j] and all of its supertypes (maintaining that every trailing argument from m - 1 onward is a subtype of p[m - 1]).
  • What if functions can be registered and unregistered dynamically between queries? Keep each index bucket as a set of function names instead of a list so registering is O(S_i) and unregistering is O(S_i) on average, plus maintain a frequency counter variadic_length_counts[m] so longest_variadic can shrink accurately whenever the last variadic signature of maximum length is removed.

Follow-up questions

Similar questions

More Confluent interview questions

All 30 Confluent questions →