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

DataEngPrep.tech
QuestionsPracticeAI CoachDashboardPricingBlog
ProLogin
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
Asked at these companies
Freight Tiger
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.

Want all answers as a PDF for offline study?
Seven focused volumes with 750+ in-depth answers — Answer Vault →

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 →
Categories
All QuestionsSQLSpark / Big DataPython / CodingSystem DesignCloud / ToolsBehavioral
By Company
AmazonGoogleDatabricksSnowflakeAWSAzureMicrosoftNetflixUberTCS
Interview Guides
All GuidesTop SQL QuestionsTop Spark QuestionsPySpark QuestionsTop Python QuestionsTop System DesignKafka QuestionsAirflow QuestionsSQL Window FunctionsETL QuestionsData Modeling
Products
AI Interview CoachAnswer AnalyzerSQL PlaygroundResume AnalyzerAnswer Vault PDFsPricing
Company
About & Editorial PolicyContact UsAI DisclosureDisclaimerTerms of ServicePrivacy Policy
© 2026 DataEngPrep.tech. All rights reserved.
AboutBlogContactDisclaimer