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"isNone(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_idonce, sorted in ascending lexicographical (alphabetical) order (equivalent to a single-columnSELECT user_id ... ORDER BY user_id ASCquery 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 orNonefor"country".
Step-by-step walkthrough
Understand the goal and the exact rules
We receive an audit log
login_attemptswhere every entry records one sign-in event with four fields:user_id,timestamp,status, andcountry. We want to identify everyuser_idwith 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,omarhas 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']- Exact status match (
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:
FROM login_attempts: Start from all log rows.WHERE status = 'SUCcEss' AND country IS NOT NULL: Filter individual rows before grouping. Failed sign-ins andNULLcountries are discarded immediately so they can never add a country to a user.GROUP BY user_id: Collapse all surviving rows for the same user into one group, guaranteeing eachuser_idappears at most once.HAVING COUNT(DISTINCT country) >= 2: Filter groups after aggregation.DISTINCTis critical: repeated sign-ins from'AU'count as1unique country, not2. We useHAVINGrather thanWHEREbecauseWHEREruns before groups exist and cannot evaluateCOUNT(...).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)ignoresNULLvalues automatically in standard SQL, soAND country IS NOT NULLserves as an explicit early filter. Also note that=is case-sensitive by default in PostgreSQL and SQLite, whereas MySQL's default collations ignore case unlessstatus COLLATE utf8mb4_bin = 'SUCcEss'is specified.Why brute force in Python is too slow, and how sets fix it
In the Python judge,
login_attemptsarrives asList[Dict[str, str]].A naive pairwise loop comparing every pair
(row_a, row_b)to check whether they share auser_id, both carrystatus == 'SUCcEss', and hold different non-Nonecountries takesn * (n - 1) / 2comparisons—around5,000,000,000operations whenn = 100,000.Instead, we mirror the SQL query in one pass using a dictionary of sets:
- The dictionary (
countries_by_user) acts likeGROUP BY user_id: each key is auser_id. - Each value is a Python
setof country codes, acting likeDISTINCT country: inserting'AU'into{"AU"}leaves the set unchanged inO(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')- The dictionary (
Phase 1 in Python: filter rows and group countries per user
Let's write Phase 1 of
find_multi_country_successful_users. Usingattempt.get("status")andattempt.get("country")safely returnsNoneif a key is missing or explicitly mapped toNone. Whenever a row fails either gate check,continueskips 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)Phases 2 & 3 in Python: filter by set size and sort alphabetically
Once
countries_by_useris populated, we translateHAVING COUNT(DISTINCT country) >= 2andORDER BY user_id:- Iterate over
(user_id, countries)incountries_by_user.items(). - Keep
user_idwheneverlen(countries) >= 2. Because dictionary keys are unique, duplicateuser_identries never occur. - 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- Iterate over
Trace Example 3 row by row
Let's verify every rule on Example 3, where
omarattempts sign-ins from'IT'and'ES'andliamsigns 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: []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, wherenis the number of rows inlogin_attemptsandkis the number of qualifying users (k <= n). We scan allnrows once, doingO(1)average-time dictionary and set lookups per row, inspect at mostndistinct users in the dictionary, and sort thekqualifyinguser_idstrings inO(k log k)time. - Space:
O(n)in the worst case. Thecountries_by_userdictionary stores one key per distinct user with a valid sign-in, and all sets combined hold at mostndistinct(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 byCOUNT(DISTINCT country)in SQL). An account with'ES'andNonehas 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 SQLiteTEXTare 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 SQLORDER BYfollows the column's collation.
Common mistakes
- Using
COUNT(country)instead ofCOUNT(DISTINCT country). WithoutDISTINCT(or using a list instead of asetin 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
WHEREin SQL. WritingWHERE COUNT(DISTINCT country) >= 2is a syntax error becauseWHEREfilters individual rows beforeGROUP BYruns; conditions on aggregate functions (functions likeCOUNTorSUMthat combine multiple rows into one value) belong inHAVING. - Returning duplicate
user_idrows. Selecting from raw rows withoutGROUP BYorDISTINCToutputs'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, writeWHERE LOWER(TRIM(status)) = 'success'. Because wrapping a column inLOWER(TRIM(...))prevents a plain index onstatusfrom being used, you would either clean the text when writing rows or create an expression index onLOWER(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
LAGthat reads a neighboring row in a sorted group without collapsing rows) partitioned byuser_idand ordered bytimestampto fetchprev_countryandprev_timestamp, then filterWHERE 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
SELECTand 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 withkey=lambda item: (-item[1], item[0])so ties in country count still break alphabetically byuser_id.
Follow-up questions
- How would your solution change if status matching had to ignore letter case and surrounding spaces?
- How would you flag accounts that complete valid sign-ins from two different countries within 60 minutes?
- What if you also needed to output each qualifying user's distinct country count, ordered from highest count to lowest?
Similar questions
- Busiest 60-Second Event Window
- Job Posting Engagement Metrics Excluding Non-Viewing Applicants
- Compute 7-Day DAU, D1 Retention, and Revenue Cohorts
- Class-Level 2024 Exam Summary with Zero-Filled Averages
- Summarizing Imaging Claims Spend and Fiscal Months
- Build Rolling User Features for Experiment Regression