Pass functions and analyze basic data structures
Company: eBay
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: Medium
Interview Round: Onsite
Implement a function applyTwice(f, x) that accepts a function f and a value x and returns f(f(x)) in your preferred language. Demonstrate how to pass functions (or delegates) as parameters and discuss closures and side effects. Then analyze arrays, linked lists, stacks, and queues: give time/space complexities for insert, delete, search, and iteration, and explain when you would choose each structure.
Quick Answer: This question evaluates proficiency with higher-order functions, passing functions or delegates, closures, and reasoning about side effects, alongside the ability to analyze fundamental data structures and their performance characteristics.
You are given a list of operations ops describing a unary integer function f and an integer x. Each operation is applied in order to transform the input. Supported operations are: "add v" (add integer v), "mul v" (multiply by integer v), "pow e" (raise to the non-negative integer exponent e), "neg" (negate), and "abs" (absolute value). If ops is empty, f is the identity function. Implement apply_twice(ops, x) to return f(f(x)).
Constraints
- 0 <= len(ops) <= 100
- Each op is one of: 'add v', 'mul v', 'pow e', 'neg', 'abs'
- v is a signed 64-bit integer; e is an integer in [0, 9]
- x is a signed 64-bit integer
- Apply operations left-to-right; 'pow e' uses integer exponentiation
- If ops is empty, return x (identity)
Solution
from typing import List\n\ndef apply_twice(ops: List[str], x: int) -> int:\n def make_func(ops: List[str]):\n def f(val: int) -> int:\n for op in ops:\n parts = op.strip().split()\n if not parts:\n continue\n name = parts[0]\n if name == 'add':\n if len(parts) != 2:\n raise ValueError('add expects 1 argument')\n v = int(parts[1])\n val += v\n elif name == 'mul':\n if len(parts) != 2:\n raise ValueError('mul expects 1 argument')\n v = int(parts[1])\n val *= v\n elif name == 'pow':\n if len(parts) != 2:\n raise ValueError('pow expects 1 argument')\n e = int(parts[1])\n if e < 0:\n raise ValueError('pow exponent must be non-negative')\n val = pow(val, e)\n elif name == 'neg':\n val = -val\n elif name == 'abs':\n val = abs(val)\n else:\n raise ValueError(f'unknown operation: {name}')\n return val\n return f\n\n f = make_func(ops)\n return f(f(x))\n