Users Signing In From Multiple Countries

Medium · Data Manipulation (SQL/Python) · Software Engineer · Onsite

Problem Statement

You are given an authentication log login_attempts, represented in Python as a list of row dictionaries matching the relational schema login_attempts(user_id TEXT, timestamp TIMESTAMP, status TEXT, country TEXT). Each entry records one sign-in event with keys "user_id", "timestamp", "status", and "country" (where "country" may be None / NULL).

Find every user_id that has valid sign-ins from two or more distinct countries, enforcing these exact rules:

  • Case-sensitive status check: A record counts as a valid sign-in if and only if its "status" string equals "SUCcEss" character-for-character. Records with "FAILED", "success", "SUCCESS", or any other spelling must be ignored.
  • Null countries excluded: A record whose "country" is None (NULL) represents an unknown location and does not count toward a user's country total.
  • Unique country count: Multiple valid sign-ins from the same country count as only one country for that user.
  • Deduplicated, sorted output: Return each qualifying user_id once, sorted in ascending lexicographical (alphabetical) order (equivalent to a single-column SELECT user_id ... ORDER BY user_id ASC query in SQL).

Examples

Example 1

Input:
login_attempts = [
    {"user_id": "priya", "timestamp": "2025-05-10 08:15:00", "status": "SUCcEss", "country": "SG"},
    {"user_id": "liam",  "timestamp": "2025-05-10 09:00:00", "status": "SUCcEss", "country": "AU"},
    {"user_id": "priya", "timestamp": "2025-05-11 14:20:00", "status": "SUCcEss", "country": "KR"},
    {"user_id": "maya",  "timestamp": "2025-05-11 16:45:00", "status": "SUCcEss", "country": "BR"},
    {"user_id": "maya",  "timestamp": "2025-05-12 07:30:00", "status": "SUCcEss", "country": "MX"},
]
Output: ["maya", "priya"]

Walk-through: "priya" signed in validly from {"SG", "KR"} (2 countries) and "maya" from {"BR", "MX"} (2 countries), while "liam" only signed in from {"AU"} (1 country). Sorting the qualifying usernames alphabetically produces ["maya", "priya"].

Example 2

Input:
login_attempts = [
    {"user_id": "noah", "timestamp": "2025-06-01 10:00:00", "status": "SUCcEss", "country": "ES"},
    {"user_id": "noah", "timestamp": "2025-06-02 10:05:00", "status": "SUCcEss", "country": "ES"},
    {"user_id": "noah", "timestamp": "2025-06-03 11:00:00", "status": "SUCcEss", "country": None},
    {"user_id": "chen", "timestamp": "2025-06-01 12:30:00", "status": "SUCcEss", "country": "SG"},
    {"user_id": "chen", "timestamp": "2025-06-04 18:00:00", "status": "SUCcEss", "country": "AU"},
]
Output: ["chen"]

Walk-through: "noah" has two "ES" entries plus a None country, leaving only 1 known distinct country ({"ES"}). "chen" has valid sign-ins from "SG" and "AU", so only "chen" qualifies.

Example 3

Input:
login_attempts = [
    {"user_id": "omar", "timestamp": "2025-07-01 07:00:00", "status": "FAILED",  "country": "IT"},
    {"user_id": "omar", "timestamp": "2025-07-01 07:05:00", "status": "SUCcEss", "country": "ES"},
    {"user_id": "omar", "timestamp": "2025-07-02 09:30:00", "status": "success", "country": "IT"},
    {"user_id": "liam", "timestamp": "2025-07-03 15:00:00", "status": "SUCcEss", "country": "AU"},
    {"user_id": "liam", "timestamp": "2025-07-04 15:10:00", "status": "SUCcEss", "country": "AU"},
]
Output: []

Walk-through: For "omar", both "FAILED" and lowercase "success" are discarded, leaving only "ES". For "liam", both valid sign-ins occur in "AU". Neither account reaches two distinct countries.

Constraints

  • 0 <= len(login_attempts) <= 10^5
  • Each dictionary contains string values for "user_id", "timestamp", and "status", and either a non-empty string or None for "country".

Step-by-step walkthrough

  1. Understand the goal and the exact rules

    We receive an audit log login_attempts where every entry records one sign-in event with four fields: user_id, timestamp, status, and country. We want to identify every user_id with valid sign-ins across at least two distinct countries, returning each qualifying username once in ascending alphabetical order.

    Before writing SQL or Python, let's lock down three subtle rules from the specification and examples:

    • Exact status match ('SUCcEss'): Notice the mixed-case spelling 'SUCcEss'. In Example 3, omar has one 'SUCcEss' row in 'ES' and one lowercase 'success' row in 'IT', and the expected output is []. Status matching is case-sensitive: only 'SUCcEss' counts. (In a live interview, always confirm whether casing is strict or normalized; we cover normalization in the follow-ups.)
    • Ignore NULL (None) countries: A missing country is unknown data rather than a real country, so it never adds to a user's country count.
    • Timestamps do not restrict qualification: Two valid sign-ins from separate countries qualify regardless of when they occurred.

    Here is Example 1 laid out as a table:

    user_id | timestamp           | status  | country
    --------+---------------------+---------+--------
    priya   | 2025-05-10 08:15:00 | SUCcEss | SG
    liam    | 2025-05-10 09:00:00 | SUCcEss | AU
    priya   | 2025-05-11 14:20:00 | SUCcEss | KR
    maya    | 2025-05-11 16:45:00 | SUCcEss | BR
    maya    | 2025-05-12 07:30:00 | SUCcEss | MX
    
    Distinct valid countries per user:
      priya -> {SG, KR}  (2 countries -> keep)
      liam  -> {AU}      (1 country   -> drop)
      maya  -> {BR, MX}  (2 countries -> keep)
    
    Sorted output: ['maya', 'priya']
    
  2. Write the SQL query clause by clause

    Writing the relational query first gives us a clean mental blueprint for the Python implementation as well. Follow the logical execution order of SQL:

    1. FROM login_attempts: Start from all log rows.
    2. WHERE status = 'SUCcEss' AND country IS NOT NULL: Filter individual rows before grouping. Failed sign-ins and NULL countries are discarded immediately so they can never add a country to a user.
    3. GROUP BY user_id: Collapse all surviving rows for the same user into one group, guaranteeing each user_id appears at most once.
    4. HAVING COUNT(DISTINCT country) >= 2: Filter groups after aggregation. DISTINCT is critical: repeated sign-ins from 'AU' count as 1 unique country, not 2. We use HAVING rather than WHERE because WHERE runs before groups exist and cannot evaluate COUNT(...).
    5. ORDER BY user_id ASC: Sort the surviving usernames alphabetically.
    -- 1. Keep only exact 'SUCcEss' rows with a non-NULL country before grouping
    SELECT user_id
    FROM login_attempts
    WHERE status = 'SUCcEss'
      AND country IS NOT NULL
    -- 2. Collapse into one group per user and require at least 2 unique countries
    GROUP BY user_id
    HAVING COUNT(DISTINCT country) >= 2
    -- 3. Sort usernames alphabetically (ascending)
    ORDER BY user_id ASC;
    

    Note that COUNT(DISTINCT country) ignores NULL values automatically in standard SQL, so AND country IS NOT NULL serves as an explicit early filter. Also note that = is case-sensitive by default in PostgreSQL and SQLite, whereas MySQL's default collations ignore case unless status COLLATE utf8mb4_bin = 'SUCcEss' is specified.

  3. Why brute force in Python is too slow, and how sets fix it

    In the Python judge, login_attempts arrives as List[Dict[str, str]].

    A naive pairwise loop comparing every pair (row_a, row_b) to check whether they share a user_id, both carry status == 'SUCcEss', and hold different non-None countries takes n * (n - 1) / 2 comparisons—around 5,000,000,000 operations when n = 100,000.

    Instead, we mirror the SQL query in one pass using a dictionary of sets:

    • The dictionary (countries_by_user) acts like GROUP BY user_id: each key is a user_id.
    • Each value is a Python set of country codes, acting like DISTINCT country: inserting 'AU' into {"AU"} leaves the set unchanged in O(1) average time.
    Incoming rows                         countries_by_user (dict of sets)
    -----------------------------------   --------------------------------------------------
    priya, SUCcEss, SG  --> passes gates --> {"priya": {"SG"}}
    liam,  SUCcEss, AU  --> passes gates --> {"priya": {"SG"}, "liam": {"AU"}}
    priya, SUCcEss, KR  --> passes gates --> {"priya": {"SG", "KR"}, "liam": {"AU"}}
    omar,  FAILED,  IT  --> blocked (status != 'SUCcEss')
    
  4. Phase 1 in Python: filter rows and group countries per user

    Let's write Phase 1 of find_multi_country_successful_users. Using attempt.get("status") and attempt.get("country") safely returns None if a key is missing or explicitly mapped to None. Whenever a row fails either gate check, continue skips straight to the next row.

    SUCCESS_STATUS = "SUCcEss"
    
    
    def find_multi_country_successful_users(login_attempts: List[Dict[str, str]]) -> List[str]:
        # countries_by_user: maps user_id -> set of distinct country codes from valid logins,
        # e.g. {"maya": {"BR", "MX"}, "liam": {"AU"}}.
        countries_by_user: Dict[str, Set[str]] = {}
    
        # Phase 1: Filter valid rows (SQL WHERE) and collect distinct countries per user (GROUP BY).
        for attempt in login_attempts:
            status = attempt.get("status")
            if status != SUCCESS_STATUS:
                # Skip failed logins or other casings before grouping so they never add a country.
                continue
    
            country = attempt.get("country")
            if country is None:
                # Ignore NULL countries, matching SQL's COUNT(DISTINCT country) behavior.
                continue
    
            user_id = attempt["user_id"]
            if user_id not in countries_by_user:
                countries_by_user[user_id] = set()
            countries_by_user[user_id].add(country)
    
  5. Phases 2 & 3 in Python: filter by set size and sort alphabetically

    Once countries_by_user is populated, we translate HAVING COUNT(DISTINCT country) >= 2 and ORDER BY user_id:

    1. Iterate over (user_id, countries) in countries_by_user.items().
    2. Keep user_id whenever len(countries) >= 2. Because dictionary keys are unique, duplicate user_id entries never occur.
    3. Call qualifying_users.sort() to order the usernames alphabetically.
        # Phase 2: Keep users with at least 2 distinct countries (SQL HAVING COUNT(DISTINCT country) >= 2).
        qualifying_users: List[str] = []
        for user_id, countries in countries_by_user.items():
            if len(countries) >= 2:
                qualifying_users.append(user_id)
    
        # Phase 3: Return unique user IDs in ascending alphabetical order (SQL ORDER BY user_id).
        qualifying_users.sort()
        return qualifying_users
    
  6. Trace Example 3 row by row

    Let's verify every rule on Example 3, where omar attempts sign-ins from 'IT' and 'ES' and liam signs in twice, yet the output is []:

    Row # | user_id | status    | country | What happens?                         | countries_by_user after row
    ------+---------+-----------+---------+---------------------------------------+-------------------------------
      1   | omar    | 'FAILED'  | 'IT'    | Skipped: status != 'SUCcEss'          | {}
      2   | omar    | 'SUCcEss' | 'ES'    | Added 'ES' to omar's set              | {'omar': {'ES'}}
      3   | omar    | 'success' | 'IT'    | Skipped: lowercase != 'SUCcEss'       | {'omar': {'ES'}}
      4   | liam    | 'SUCcEss' | 'AU'    | Added 'AU' to liam's set              | {'omar': {'ES'}, 'liam': {'AU'}}
      5   | liam    | 'SUCcEss' | 'AU'    | 'AU' already in liam's set (no dupes) | {'omar': {'ES'}, 'liam': {'AU'}}
    
    Filter len(countries) >= 2:
      omar has len({'ES'}) == 1 -> excluded
      liam has len({'AU'}) == 1 -> excluded
    
    Final result: []
    
  7. Complete solution

    Putting all three phases together gives the complete implementation:

    from typing import Any, Dict, List, Optional, Set, Tuple
    
    # Example 3 requires an exact, case-sensitive match on 'SUCcEss'
    # (a lowercase 'success' row there must not count).
    SUCCESS_STATUS = "SUCcEss"
    
    
    def find_multi_country_successful_users(login_attempts: List[Dict[str, str]]) -> List[str]:
        # countries_by_user: maps user_id -> set of distinct country codes from valid logins,
        # e.g. {"maya": {"BR", "MX"}, "liam": {"AU"}}.
        countries_by_user: Dict[str, Set[str]] = {}
    
        # Phase 1: Filter valid rows (SQL WHERE) and collect distinct countries per user (GROUP BY).
        for attempt in login_attempts:
            status = attempt.get("status")
            if status != SUCCESS_STATUS:
                # Skip failed logins or other casings before grouping so they never add a country.
                continue
    
            country = attempt.get("country")
            if country is None:
                # Ignore NULL countries, matching SQL's COUNT(DISTINCT country) behavior.
                continue
    
            user_id = attempt["user_id"]
            if user_id not in countries_by_user:
                countries_by_user[user_id] = set()
            countries_by_user[user_id].add(country)
    
        # Phase 2: Keep users with at least 2 distinct countries (SQL HAVING COUNT(DISTINCT country) >= 2).
        qualifying_users: List[str] = []
        for user_id, countries in countries_by_user.items():
            if len(countries) >= 2:
                qualifying_users.append(user_id)
    
        # Phase 3: Return unique user IDs in ascending alphabetical order (SQL ORDER BY user_id).
        qualifying_users.sort()
        return qualifying_users
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Imagine giving every account its own country stamp book, like a passport. As we read the sign-in log one row at a time, we act like a border agent checking two rules before stamping anything: is the status string literally 'SUCcEss', and is the country known (not NULL)? Only when both checks pass do we stamp that country into the account's book—and if that country's stamp is already present, we do not add a second copy. At the end, we collect every user whose book holds at least two stamps and sort those usernames alphabetically.

A naive approach that compares every pair of log rows to look for two different countries for the same user takes O(n^2) work, which becomes painfully slow when a log has hundreds of thousands of rows. Another common trap is counting total valid sign-ins per user (COUNT(*) in SQL or a plain integer counter in Python), which mistakenly flags someone who signed in five times from the same country. Instead, we pair a hash map (a key-value dictionary that looks up a user in O(1) average time) with a hash set (a collection that keeps only unique items in O(1) average time), mirroring SQL's GROUP BY user_id and COUNT(DISTINCT country).

Let's trace a tiny 5-row log: 1. (maya, SUCcEss, BR) -> passes both checks -> maya gets {"BR"}. 2. (omar, SUCcEss, ES) -> passes both checks -> omar gets {"ES"}. 3. (omar, FAILED, IT) -> rejected because status is not 'SUCcEss' -> omar stays {"ES"}. 4. (noah, SUCcEss, AU) then (noah, SUCcEss, AU) -> both pass, but 'AU' is already in noah's set -> noah stays {"AU"}. 5. (maya, SUCcEss, MX) -> passes both checks -> maya gets {"BR", "MX"} (2 countries).

Only maya reaches at least 2 distinct countries, so the sorted output is ['maya'].

Complexity

  • Time: O(n + k log k) on average, where n is the number of rows in login_attempts and k is the number of qualifying users (k <= n). We scan all n rows once, doing O(1) average-time dictionary and set lookups per row, inspect at most n distinct users in the dictionary, and sort the k qualifying user_id strings in O(k log k) time.
  • Space: O(n) in the worst case. The countries_by_user dictionary stores one key per distinct user with a valid sign-in, and all sets combined hold at most n distinct (user_id, country) pairs.

In SQL, the engine scans the table once and groups rows by user_id (using hashing or sorting). Adding a covering index (a database index that contains every column the query reads so the engine never has to fetch the full table rows) on (status, user_id, country) lets the database jump straight to 'SUCcEss' entries, already ordered by user_id and country.

Edge cases

  • Empty input ([]): No users enter the dictionary, so the function returns [].
  • Repeated sign-ins from the same country: Ten 'SUCcEss' sign-ins from 'ES' still produce the 1-element set {"ES"}, so the user is excluded.
  • Failed sign-ins from a second country: Filtered out before grouping, so 'SUCcEss' in 'ES' plus 'FAILED' in 'IT' leaves only {"ES"}.
  • NULL (None) country: Skipped explicitly in Python (and ignored automatically by COUNT(DISTINCT country) in SQL). An account with 'ES' and None has only 1 known country and does not qualify.
  • Case sensitivity of status: Only 'SUCcEss' matches (Example 3). Lowercase 'success' and uppercase 'SUCCESS' are skipped. In SQL, collation (the set of rules a database uses to compare and sort text) determines whether = is case-sensitive: PostgreSQL and SQLite TEXT are case-sensitive by default, while MySQL's default collations are case-insensitive unless a binary collation is specified.
  • Mixed-case usernames when sorting: Python's .sort() orders strings by Unicode code point (all uppercase ASCII letters come before lowercase ones, so 'Maya' precedes 'chen'), whereas SQL ORDER BY follows the column's collation.

Common mistakes

  • Using COUNT(country) instead of COUNT(DISTINCT country). Without DISTINCT (or using a list instead of a set in Python), two sign-ins from the same country count as 2 and falsely qualify the user.
  • Filtering for 'SUCcEss' after grouping. Checking "user visited >= 2 countries across all rows AND had >= 1 valid sign-in" wrongly includes someone who succeeded in 'ES' and failed a sign-in from 'IT'. Both countries must come from 'SUCcEss' records.
  • Putting an aggregate inside WHERE in SQL. Writing WHERE COUNT(DISTINCT country) >= 2 is a syntax error because WHERE filters individual rows before GROUP BY runs; conditions on aggregate functions (functions like COUNT or SUM that combine multiple rows into one value) belong in HAVING.
  • Returning duplicate user_id rows. Selecting from raw rows without GROUP BY or DISTINCT outputs 'priya' multiple times if she signed in from three countries.

Follow-up questions

  • How would your solution change if status matching had to ignore letter case and surrounding spaces? Confirm this rule first because it changes Example 3's output to ['omar']. In Python, normalize safely with (attempt.get("status") or "").strip().lower() == "success"; in SQL, write WHERE LOWER(TRIM(status)) = 'success'. Because wrapping a column in LOWER(TRIM(...)) prevents a plain index on status from being used, you would either clean the text when writing rows or create an expression index on LOWER(TRIM(status)).
  • How would you flag accounts that complete valid sign-ins from two different countries within 60 minutes? Sort each user's valid sign-ins chronologically and compare each event only to the immediately preceding valid event for that user—if any two valid sign-ins in different countries occur within 60 minutes, some adjacent pair in between must also switch countries within at most 60 minutes. In SQL, use a window function (a function like LAG that reads a neighboring row in a sorted group without collapsing rows) partitioned by user_id and ordered by timestamp to fetch prev_country and prev_timestamp, then filter WHERE country <> prev_country AND timestamp - prev_timestamp <= INTERVAL '60 minutes'.
  • What if you also needed to output each qualifying user's distinct country count, ordered from highest count to lowest? In SQL, include the aggregate in SELECT and sort by it: SELECT user_id, COUNT(DISTINCT country) AS country_count ... GROUP BY user_id HAVING COUNT(DISTINCT country) >= 2 ORDER BY country_count DESC, user_id ASC. In Python, append (user_id, len(countries)) and sort with key=lambda item: (-item[1], item[0]) so ties in country count still break alphabetically by user_id.

Follow-up questions

Similar questions

More Marshall Wace interview questions

All 2 Marshall Wace questions →