Make membership linear-time overall

Problem

Implement all_present(xs, ys), returning whether every distinct value in xs occurs in ys. Construct at most one auxiliary collection so expected time is O(len(xs) + len(ys)).

Starter code

def all_present(xs, ys):
    pass
Reveal answer or reference solution
def all_present(xs, ys):
    lookup = set(ys)
    return all(x in lookup for x in xs)

Public tests

  • all_present([1,2,2], [3,2,1])True
  • all_present([1,4], [1,2,3])False
  • all_present([], [])True

Local history

Loading attempts saved in this browser…

Use with your agent

Share this URL and your attempt. Ask the agent to start with a clarifying question or the smallest useful hint.

Tutor me on https://mlprep.iwase.dev/programming/python/original-py-complexity/. If window.mlPrepAgent is available, read attempts for item original-py-complexity before tutoring. Inspect my attempt, keep the item ID, and do not reveal the full answer first. After a real attempt, append its record and read it back.

Appears in