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 queryqif and only iflen(q) == len(param_types[i])andq[j] == param_types[i][j]at every indexj. - Variadic (
is_variadic[i] == True, withm = len(param_types[i]) >= 1): accepts queryqif and only iflen(q) >= m, every fixed leading slot0 <= j < m - 1satisfiesq[j] == param_types[i][j], and every trailing slotm - 1 <= j < len(q)equalsparam_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^4andlen(param_types) == len(is_variadic) == len(names)- Every name in
namesis distinct, has length1to30, and consists ofA-Z,a-z,0-9, and_. 0 <= len(param_types[i]) <= 20, withlen(param_types[i]) >= 1wheneveris_variadic[i]isTrue.- Every type name has length
1to20and consists ofA-Z,a-z,0-9, and_. 1 <= len(queries) <= 10^4,0 <= len(queries[j]) <= 100, and the sum oflen(q)over all queries is at most2 * 10^5.- Across all queries combined, at most
10^6function names appear in the returned output.
Step-by-step walkthrough
Understand exact vs. variadic matching
We receive a registry of callable declarations — each given by
names[i], its parameter type sequenceparam_types[i], and a boolean flagis_variadic[i]— together with a list of call-sitequeries. For every queryq, we must return all matching function names sorted in standard ascending string order.Compare the two matching rules carefully:
- Non-variadic (
is_variadic == False): Matchesqif and only ifq == param_types[i](identical length and identical case-sensitive type at every index). - Variadic (
is_variadic == True, withm = len(param_types[i]) >= 1): Leading slots0 .. m - 2matchqindex-for-index, while the trailing typeparam_types[i][m - 1]repeats one or more times across the rest ofq(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)- Non-variadic (
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 TrueWith up to
F = 10^4functions andQ = 10^4queries, nested loops performF * Q = 10^8function checks, each scanning up to100argument types. That is billions of operations in Python. Instead of scanning allFfunctions per query, we want to index the library once and look up only the signatures that could matchq.Key insight: every matching variadic signature is a prefix of the query
Suppose a variadic function with parameter list
pof lengthmaccepts a non-empty queryq. What mustplook like?- Its fixed leading parameters
p[0 .. m - 2]equalq[0 .. m - 2]. - Its variadic parameter
p[m - 1]equalsq[m - 1](the very first repeated slot), and also equalsq[m], q[m + 1], ..., q[len(q) - 1].
Putting
(1)and the first part of(2)together gives a huge simplification:pmust equalq[:m], the length-mprefix ofq!And which prefix lengths
msatisfy the second part of(2)(thatq[m - 1 :]is all one identical type)? Letrun_startbe the earliest index where the trailing streak of identical types at the end ofqbegins. Thenq[m - 1 :]is all one type if and only ifm - 1 >= run_start, which rearranges tom >= 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 a100-element query, we check at most 20 prefixes!- Its fixed leading parameters
Index the function library by parameter tuple
We build two hash maps before answering any queries:
exact_index: mapstuple(param_types[i]) -> [function names]for non-variadic functions.variadic_index: mapstuple(param_types[i]) -> [function names]for variadic functions.
Why convert
param_types[i]to atupleinstead 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)Find where the trailing streak of identical types begins
For any non-empty query
q, start a pointerstartat the last indexlen(q) - 1and step leftward as long as the element to the left (q[start - 1]) matchesq[-1]:q = ["str", "int", "float", "float"] start = 3 ("float"): q[2] == "float" -> decrement to 2 start = 2 ("float"): q[1] == "int" != "float" -> stop! return 2def 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 startAnswer each query and trace Example 1
For each
query:- Convert
querytoquery_key = tuple(query)once. - Copy any exact matches via
matches = list(exact_index.get(query_key, [])). Making a freshlist(...)copy is essential — otherwisematches.extend(...)andmatches.sort()would mutate the list stored insideexact_indexand corrupt later queries! - If
queryis non-empty, computefirst_m = last_run_start(query) + 1andlast_m = min(len(query), longest_variadic), and appendvariadic_index.get(query_key[:m], [])for eachminrange(first_m, last_m + 1). Everymhas a distinct tuple length, so no function can ever be added twice. - Sort
matchesand append toresults.
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 -> []- Convert
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...):
- Exact lookup: Check
exact_index[("a", "b", "b", "b")]-> finds"exact". - Find the trailing run: Walking left from index
3("b"), indices1, 2, 3are all"b", while index0is"a", sorun_start = 1. - Probe valid variadic prefix lengths
mfromrun_start + 1 = 2to4: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",)fora1) is skipped automatically because1 < run_start + 1, reflecting that"a"cannot repeat across"b"s.
- 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 theFfunctions once, converting each parameter list into a hashable key (an immutabletuplethat Python can hash into a dictionary) and appending its name inO(1)average time per function. - Time per query:
O(L + min(L, K)^2 + R log R)average time. Convertingqueryto a tuple and scanning its trailing run both takeO(L)steps. Next, slicing and hashing prefixesquery_key[:m]formup tomin(L, K)touches at most1 + 2 + ... + K = K * (K + 1) / 2elements (<= 210string references sinceK <= 20, independent ofF!). Finally, sorting theRmatched names takesO(R log R)string comparisons. Across allQqueries, total work is linear in the library size and query input plusO(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)andsendMany(bytes...)both match["bytes"]without colliding becauseexact_indexandvariadic_indexare 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, sorange(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), soplot(str, int, float...)must not match["str", "int"]. - Probing only one variadic prefix length: Checking only
m = run_start + 1or onlym = len(q)misses valid signatures likeabb(a, b, b...)on["a", "b", "b", "b"]. - Mutating the list stored inside
exact_index: Writingmatches = exact_index.get(query_key, [])without wrapping inlist(...)causesmatches.extend(...)to permanently append variadic functions intoexact_index, corrupting subsequent identical queries! - Joining type names without a safe delimiter (
"".join(params)): Collides["int", "s"]with["i", "nts"]; usingtuple(params)avoids string-concatenation collisions altogether. - Calling
last_run_starton an empty query[]: Guard withif query:first solen(query) - 1never indexes-1on an empty list.
Alternative approaches
- Trie of variadic signatures: A trie (a prefix tree where each edge is one parameter type) lets you walk
querydown one step at a time fromm = 1tomin(L, K)and collect variadic functions at every depthm >= run_start + 1. That trims the variadic lookup cost fromO(min(L, K)^2)tuple slicing toO(min(L, K)), which pays off ifKcould be thousands rather than20. - Memoizing repeated queries: If real call-site workloads repeat the exact same
tuple(query)thousands of times, cachingquery_key -> sorted_matchesanswers duplicates inO(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 anAmbiguousCallErrorrather than picking arbitrarily. - What changes if types form an inheritance hierarchy (subtyping), such as
DogmatchingAnimal? Direct tuple hashing no longer works because one argument typeDogcan matchDog,Mammal, orAnimal. Instead, store signatures in a trie keyed by parameter type and traverse it via DFS/backtracking: at argument positionj, branch across edges forquery[j]and all of its supertypes (maintaining that every trailing argument fromm - 1onward is a subtype ofp[m - 1]). - What if functions can be registered and unregistered dynamically between queries? Keep each index bucket as a
setof function names instead of alistso registering isO(S_i)and unregistering isO(S_i)on average, plus maintain a frequency countervariadic_length_counts[m]solongest_variadiccan shrink accurately whenever the last variadic signature of maximum length is removed.
Follow-up questions
- How would you return only the single most specific overload instead of every matching function?
- What changes if types form an inheritance hierarchy (subtyping), such as `Dog` matching `Animal`?
- What if functions can be registered and unregistered dynamically between queries?
Similar questions
- Validate Consistency of a Partial 9x9 Sudoku Grid
- Backward File Tailer and Heartbeat Monitor
- Streaming File Tail and Minimum-Monster Dungeon Path
- Read the Last N Lines
- Pod Counter Management with Broadcast Increments
- Pairwise Majority Song Ranking
More Confluent interview questions
- Indexed Whole-Word and Sequential Phrase Search Over Documents Medium
- Validate Consistency of a Partial 9x9 Sudoku Grid Medium
- Verify and Lexicographically Solve a 9x9 Sudoku Grid Medium Pro
- Backward Chunked Reader for Trailing File Lines Medium Pro
- News Aggregator and Disposable Inbox Platform Medium Pro
- Scalable Podcast Ingestion and Subscriber Feed Medium Pro
- LRU Cache Supporting O(1) Running Mean Medium Pro
- In-Memory Document Search with Phrase and Boolean Queries Medium Pro
- Linux Process Execution, Filesystem Internals, and Container Isolation Medium Pro
- Variadic Functions and Typesafe Structured Logging Hard Pro