🍪

Essential cookies keep authentication working. With your permission, we also use analytics to improve the product. Privacy Policy

DDataEngPrep.tech
Home
PricingBlog
Sign InStart Free→
Home/Questions/Python/Coding/How many cities does each department operate in? List the top 3 departments in terms of the most number of cities. In case of a tie, order by dept_id.

How many cities does each department operate in? List the top 3 departments in terms of the most number of cities. In case of a tie, order by dept_id.

Python/Codingmedium2 min read

Reviewed by Aditya Kumar · Last reviewed 2026-08-08

To determine the number of cities each department operates in and list the top 3, you'll group the data by department, count the distinct cities, and then order the results to select the top entries,…

🤖 Analyze Your Answer
Frequency
Low
Asked at 1 company
Category
179
questions in Python/Coding
Difficulty Split
127E|24M|28H
in this category
Total Bank
1,863
across 7 categories
Part of the Python for Data Engineers Interview Preparation Hub
Explore Python for Data Engineers Hub→
Reported in Interview Loops AtClick to view company-specific questions
🏢 Freight Tiger Interview Hub→
Key Concepts Tested
sql

Why This Question Matters

This medium-level Python/Coding question appears frequently in data engineering interviews at companies like Freight Tiger. While less common, it tests deeper understanding that distinguishes strong candidates. Mastering the underlying concepts (sql) will help you answer variations of this question confidently.

How to Approach This

Break this problem into components. Identify the core trade-offs involved, then walk the interviewer through your reasoning step by step. Demonstrate awareness of edge cases and production considerations - this is what separates good answers from great ones. The expert answer includes a code example that demonstrates the implementation pattern.

Expert Answer
376 wordsIncludes code

To determine the number of cities each department operates in and list the top 3, you'll group the data by department, count the distinct cities, and then order the results to select the top entries, handling ties as specified.

Mechanics and Why

The core of the solution involves aggregating data. First, GROUP BY dept_id combines all records for a given department. Within each group, COUNT(DISTINCT city) calculates the unique number of cities. To identify the "top 3," the results are then sorted by city_count in descending order. The question explicitly states, "In case of a tie, order by dept_id," which means dept_id should be used as a secondary sort key in ascending order. Finally, LIMIT 3 selects only the top three departments based on this sorting logic.

While window functions like RANK() or DENSE_RANK() could be used to assign ranks, the ORDER BY ... LIMIT 3 approach directly answers the question's requirement for exactly three departments, using dept_id to deterministically break ties if multiple departments share the same city_count at the third position.

Example and Trade-offs

Consider a table named department_operations with columns dept_id and city.
SELECT
    dept_id,
    COUNT(DISTINCT city) AS city_count
FROM
    department_operations
GROUP BY
    dept_id
ORDER BY
    city_count DESC,
    dept_id ASC
LIMIT 3;

Performance Considerations:
COUNT(DISTINCT) can be an expensive operation, especially on large datasets, as it often requires a full data scan and significant data shuffling across nodes to ensure uniqueness before aggregation. In systems like Apache Spark, this translates to high network I/O and CPU usage during the shuffle phase. For data warehouses like Snowflake, while micro-partition pruning can optimize initial data access, the aggregation still demands computational resources. GROUP BY and ORDER BY operations also involve sorting and potential shuffling, impacting query performance. For frequently queried top-N metrics, consider pre-aggregating this data into a materialized view or a dbt model.

In the interview, also mention…

Clarify with the interviewer if "top 3 departments" means strictly three rows (as achieved by LIMIT 3) or "up to three ranks" (which might return more than three rows if multiple departments tie for the 3rd rank, requiring RANK() or DENSE_RANK() and filtering). Also, discuss the implications of data volume on query performance and potential optimization strategies for very large datasets.
⚡
Pro Tip

Pro-Move: RANK vs DENSE_RANK. Red Flag: LIMIT 3 without tie handling.

Get The Complete 2026 FDE, AI & DE Master Vault (All 9 PDF Volumes)
FDE Interview Guide, FastMCP & RAG Playbook, and 7-Volume DE Vault with 1,863+ answers →
⭐ Save 45%

Related Python/Coding Questions

easyWhat are traits in Scala, and how are they different from classes?FreemediumWrite a Python function to check if a string is a palindrome.FreeeasyWhat is the difference between a list and a tuple in Python?FreeeasyExplain the difference between shallow copy and deep copy in Python.FreeeasyWrite a Python function to find the first non-repeating character in a string.Free

Level up your prep

Recommended
Educative
Educative Unlimited

800+ hands-on courses — Grokking System Design, Coding Patterns, and AI mock interviews for your DE loop.

Start learning →

Some links below are affiliate links. If you buy through them we may earn a small commission at no extra cost to you — it helps keep DataEngPrep free.

According to DataEngPrep.tech, this is one of the most frequently asked Python/Coding interview questions, reported at 1 company. DataEngPrep.tech maintains an editor-reviewed database of 1,863 data engineering interview questions across 7 categories.

← Back to all questionsMore Python/Coding questions →
Topic Hubs
All Topic Hubs (12 Competencies) →All 1,863+ QuestionsSQL Interview QuestionsApache Spark QuestionsPySpark QuestionsPython for Data EngineersSystem Design InterviewData Modeling & WarehousingStreaming (Kafka/Flink)SQL Window FunctionsETL Pipeline Design
Company Hubs
All Company Hubs (100+ Companies) →AmazonGoogleMetaDatabricksSnowflakeNetflixUberStripeMicrosoftAppleGoldman SachsAWS Engineering
Academies & Guides
All Guides & ArticlesData Engineering AcademyForward Deployed AI AcademyClient Simulation StudioApache Airflow QuestionsAzure Data EngineerBehavioral & STAR MethodCloud & Distributed Tools
AI Tools & Products
Answer Analyzer (Free)AI Mock InterviewsSQL PlaygroundATS Resume AnalyzerOffline PDF Answer VaultsMembership & Pricing
Company
About & Editorial PolicyContact UsAI DisclosureDisclaimerTerms of ServicePrivacy Policy
© 2026 DataEngPrep.tech. All rights reserved.
AboutBlogContactDisclaimer