{"id":10059,"date":"2025-09-11T13:53:13","date_gmt":"2025-09-11T08:23:13","guid":{"rendered":"https:\/\/namastedev.com\/blog\/?p=10059"},"modified":"2025-09-11T15:06:45","modified_gmt":"2025-09-11T09:36:45","slug":"two-city-scheduling","status":"publish","type":"post","link":"https:\/\/namastedev.com\/blog\/two-city-scheduling\/","title":{"rendered":"Two City Scheduling"},"content":{"rendered":"\n<!-- Greedy: 2 -->\n<!-- PrismJS for Syntax Highlighting -->\n<link href=\"https:\/\/cdn.jsdelivr.net\/npm\/prismjs@1.29.0\/themes\/prism-tomorrow.min.css\" rel=\"stylesheet\">\n<script src=\"https:\/\/cdn.jsdelivr.net\/npm\/prismjs@1.29.0\/prism.min.js\"><\/script>\n<script src=\"https:\/\/cdn.jsdelivr.net\/npm\/prismjs@1.29.0\/plugins\/autoloader\/prism-autoloader.min.js\"><\/script>\n\n<style>\n.wp_blog_theme {\n  --primary: #E58C32;\n  --secondary: #030302;\n  --light-bg: #fef9f4;\n  --text-dark: #2d2d2d;\n  --tab-radius: 12px;\n  --shadow: 0 4px 12px rgba(0, 0, 0, 0.08);\n  --code-bg: #001f3f;\n  --code-text: #d4f1ff;\n}\n\n.wp_blog_container {\n  font-family: 'Segoe UI', sans-serif;\n  background: var(--light-bg);\n  margin: 0;\n  padding: 0;\n  color: var(--text-dark);\n}\n\n\/* Heading *\/\n.wp_blog_main-heading {\n  text-align: center;\n  font-size: 2.4rem;\n  color: var(--primary);\n  margin-top: 2.5rem;\n  font-weight: bold;\n}\n\n\/* Explanation Card *\/\n.wp_blog_explanation,\n.wp_blog_code-tabs-container {\n  max-width: 940px;\n  margin: 2rem auto;\n  padding: 2rem;\n  background: white;\n  border-radius: var(--tab-radius);\n  box-shadow: var(--shadow);\n}\n\n\/* Text and Visuals *\/\n.wp_blog_explanation h2 {\n  font-size: 1.4rem;\n  color: var(--primary);\n  margin-bottom: 0.5rem;\n}\n\n.wp_blog_explanation p,\n.wp_blog_explanation li {\n  font-size: 1.05rem;\n  line-height: 1.7;\n  margin: 0.5rem 0;\n}\n\n.wp_blog_explanation code {\n  background: #fef9f4;   \/* light bg instead of dark blue *\/\n  color: #E58C32;        \/* brand orange *\/\n  padding: 3px 6px;\n  border-radius: 4px;\n  font-family: 'Courier New', monospace;\n  font-weight: 600;      \/* optional, makes it pop *\/\n}\n\n.wp_blog_explanation img {\n  max-width: 100%;\n  border-radius: var(--tab-radius);\n  margin-top: 1rem;\n  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.06);\n}\n\n\/* Tab Buttons *\/\n.wp_blog_code-tabs-header {\n  display: flex;\n  flex-wrap: wrap;\n  gap: 0.5rem;\n  margin-bottom: 1rem;\n}\n\n.wp_blog_code-tab-button {\n  padding: 0.6rem 1.2rem;\n  border: 1px solid var(--primary);\n  background: white;\n  color: var(--primary);\n  border-radius: 50px;\n  font-weight: 600;\n  cursor: pointer;\n  transition: all 0.3s ease;\n}\n\n.wp_blog_code-tab-button:hover {\n  background: var(--secondary);\n}\n\n.wp_blog_code-tab-button.active {\n  background: var(--primary);\n  color: white;\n}\n\n\/* Code Content *\/\n.wp_blog_code-tab-content {\n  display: none;\n  background: var(--code-bg);\n  border-radius: var(--tab-radius);\n}\n\n.wp_blog_code-tab-content.active {\n  display: block;\n}\n\n.wp_blog_code-tab-content pre {\n  margin: 0;\n  padding: 1.5rem;\n  font-size: 1rem;\n  overflow-x: auto;\n  background: var(--code-bg);\n  border-radius: var(--tab-radius);\n  color: var(--code-text);\n}\n\n\/* Dark mode variables *\/\n.wp_blog_theme.dark-mode {\n  --light-bg: #121212;\n  --text-dark: #f5f5f5;\n  --shadow: 0 4px 12px rgba(255, 255, 255, 0.08);\n  --code-bg: #1e1e1e;\n  --code-text: #c5f0ff;\n}\n\n.wp_blog_theme.dark-mode .wp_blog_explanation {\n  background: #1e1e1e;\n}\n\n\/* Dark mode code highlight *\/\n.wp_blog_theme.dark-mode .wp_blog_explanation code {\n  background: #333;\n  color: #ffd27f;\n}\n\n.wp_blog_theme {\n  position: relative; \/* makes it the reference for absolute children *\/\n}\n\n.wp_blog_toggle-btn {\n  position: absolute;\n  top: 1rem;\n  right: 1rem;\n  z-index: 9999;\n  padding: 0.5rem 0.8rem;\n  border-radius: 10%;\n  background: var(--primary);\n  color: white;\n  font-weight: bold;\n  cursor: pointer;\n  border: none;\n  box-shadow: var(--shadow);\n  transition: background 0.3s, transform 0.2s;\n}\n\n.wp_blog_toggle-btn:hover {\n  background: #cc772e;\n}\n\n.wp_blog_theme.dark-mode .wp_blog_code-tabs-container {\n  background: #1e1e1e;\n}\n<\/style>\n\n<div class=\"wp_blog_container wp_blog_theme\">\n  <button id=\"blogNotesThemeToggle\" class=\"wp_blog_toggle-btn\">\ud83c\udf19<\/button>\n  <h1 class=\"wp_blog_main-heading\"><\/h1>\n\n  <div class=\"wp_blog_explanation\">\n    <h2>Problem Statement:<\/h2>\n   \n  <p>\n    A company is planning to interview <code>2n<\/code> people. Given the array <code>costs<\/code> where <code>costs[i] = [aCost<sub>i<\/sub>, bCost<sub>i<\/sub>]<\/code>, the cost of flying the <code>i<sup>th<\/sup><\/code> person to city <code>a<\/code> is <code>aCost<sub>i<\/sub><\/code>, and the cost of flying the <code>i<sup>th<\/sup><\/code> person to city <code>b<\/code> is <code>bCost<sub>i<\/sub><\/code>.\n  <\/p>\n<p>Return <i> the minimum cost to fly every person to a city such that exactly n people arrive in each city.<\/i><\/p>\n    \n    <h3>Example 1:<\/h2>\n    <p><strong>Input:<\/strong> costs = [[10,20],[30,200],[400,50],[30,20]]\n<\/p>\n    <p><strong>Output:<\/strong> 110<\/p>\n    <p><strong>Explanation:<\/strong> <\/p>\n    <ul><strong>\n        <li>The first person goes to city A for a cost of 10.<\/li>\n        <li>The second person goes to city A for a cost of 30.<\/li>\n        <li>The third person goes to city B for a cost of 50.<\/li>\n        <li>The fourth person goes to city B for a cost of 20.<\/li>\n        <\/strong>\n    <\/ul>\n\n    <p>The total minimum cost is 10 + 30 + 50 + 20 = 110 to have half the people interviewing in each city.<\/p>\n\n    <h3>Example 2:<\/h3>\n    <p><strong>Input: <\/strong>costs = [[259,770],[448,54],[926,667],[184,139],[840,118],[577,469]]<\/p>\n    <p><strong>Output: <\/strong>1859<\/p>\n\n    <h3>Example 3:<\/h3>\n    <p><strong>Input: <\/strong>costs = [[515,563],[451,713],[537,709],[343,819],[855,779],[457,60],[650,359],[631,42]]<\/p>\n    <p><strong>Output: <\/strong>3086<\/p>\n\n\n    <h3>Constraints<\/h3>\n    <ul>\n        <li><code>2 * n == costs.length<\/code><\/li>\n        <li><code>2 <= costs.length <= 100<\/code><\/li>\n        <li><code>costs.length<\/code> is even.<\/li>\n        <li><code>1 <= aCost<sub>i<\/sub>, bCost<sub>i<\/sub> <= 1000<\/code><\/li>\n    <\/ul>\n<h2>Approach:<\/h2>\n    <ul>\n        <li>For each person, calculate the <code>cost difference<\/code> between going to city A and city B.<\/li>\n        <li><strong>Sort people based on this difference<\/strong>, those who save more by going to city A come first.<\/li>\n        <li>Send the <code>first half<\/code> of people to city A and the second half to city B.<\/li>\n        <li>Add up the total cost accordingly and <code>return the answer<\/code>.<\/li>\n    <\/ul>\n\n    <h2>Time & Space Complexity:<\/h2>\n    <p><strong>Time Complexity:<\/strong> <code>O(nlogn+n)=O(nlogn)<\/code><\/p>\n    <p><strong>Space Complexity:<\/strong> <code>O(n)<\/code> Due to sort implementation<\/p>\n\n    \n<h2>Dry Run<\/h2>\n<div style=\"background: var(--light-bg); border-left: 4px solid var(--primary); padding: 1rem; border-radius: var(--tab-radius); margin: 1rem 0; color: var(--text-dark);\">\n  <p><strong>Input:<\/strong> <code>costs = [[10,20],[30,200],[50,20],[30,20]]<\/code><\/p>\n  <pre style=\"white-space: pre-wrap; background: var(--code-bg); padding: 1rem; border-radius: 8px; overflow-x: auto; color: var(--code-text);\">\n\nStep 1: Sort the array\nSorting rule = (b[1] - b[0]) - (a[1] - a[0]) \u2192 Calculate differences (cost to B - cost to A):\n[10,20] \u2192 10\n[30,200] \u2192 170\n[50,20] \u2192 -30\n[30,20] \u2192 -10\n\ncosts = [[10,20],[30,200],[50,20],[30,20]]\n\nAfter sorting (descending order of difference):\ncosts = [[30,200], [10,20], [30,20], [50,20]]\n\nStep 2: Initialize\nans = 0\nn = costs.length \/ 2 = 4 \/ 2 = 2\n\nStep 3: Assign first n people to city A\ni = 0 \u2192 costs[0][0] = 30 \u2192 ans = 30\ni = 1 \u2192 costs[1][0] = 10 \u2192 ans = 40\n\nStep 4: Assign remaining people to city B\ni = 2 \u2192 costs[2][1] = 20 \u2192 ans = 60\ni = 3 \u2192 costs[3][1] = 20 \u2192 ans = 80\n\nStep 5: Return result\nans = 80\n  <\/pre>\n  <p><strong>Output:<\/strong> <code>Result: 80<\/code><\/p>\n<\/div>\n\n<\/div>\n\n  <div class=\"wp_blog_code-tabs-container\">\n    <div class=\"wp_blog_code-tabs-header\">\n      <button class=\"wp_blog_code-tab-button active\" data-lang=\"js\">JavaScript<\/button>\n      <button class=\"wp_blog_code-tab-button\" data-lang=\"py\">Python<\/button>\n      <button class=\"wp_blog_code-tab-button\" data-lang=\"java\">Java<\/button>\n      <button class=\"wp_blog_code-tab-button\" data-lang=\"cpp\">C++<\/button>\n      <button class=\"wp_blog_code-tab-button\" data-lang=\"c\">C<\/button>\n      <button class=\"wp_blog_code-tab-button\" data-lang=\"cs\">C#<\/button>\n    <\/div>\n\n    <div class=\"wp_blog_code-tab-content active\" data-lang=\"js\">\n      <pre><code class=\"language-javascript\">\n    var twoCitySchedCost = function (costs) {\n        costs.sort((a, b) => (b[1] - b[0]) - (a[1] - a[0]));\n        let ans = 0;\n        let n = costs.length \/ 2;\n\n        for (let i = 0; i < n; i++) {\n            ans += costs[i][0];\n        }\n        for (let i = n; i < 2 * n; i++) {\n            ans += costs[i][1];\n        }\n\n        return ans;\n        };\n      <\/code><\/pre>\n    <\/div>\n\n    <div class=\"wp_blog_code-tab-content\" data-lang=\"py\">\n      <pre><code class=\"language-python\">\ndef twoCitySchedCost(costs):\n    # sort descending by (cost[1] - cost[0])\n    costs.sort(key=lambda x: x[1] - x[0], reverse=True)\n    n = len(costs) \/\/ 2\n    ans = sum(cost[0] for cost in costs[:n]) + sum(cost[1] for cost in costs[n:])\n    return ans\n\nif __name__ == \"__main__\":\n    costs = [[10,20],[30,200],[400,50],[30,20]]\n    print(twoCitySchedCost(costs))  # prints result\n\n      <\/code><\/pre>\n    <\/div>\n\n    <div class=\"wp_blog_code-tab-content\" data-lang=\"java\">\n      <pre><code class=\"language-java\">\nimport java.util.Arrays;\nimport java.util.Comparator;\n\npublic class TwoCity {\n    public static int twoCitySchedCost(int[][] costs) {\n        Arrays.sort(costs, new Comparator<int[]>() {\n            public int compare(int[] a, int[] b) {\n                \/\/ sort descending by (cost[1] - cost[0])\n                return (b[1] - b[0]) - (a[1] - a[0]);\n            }\n        });\n        int n = costs.length \/ 2;\n        int ans = 0;\n        for (int i = 0; i < n; i++) ans += costs[i][0];\n        for (int i = n; i < costs.length; i++) ans += costs[i][1];\n        return ans;\n    }\n    public static void main(String[] args) {\n        int[][] costs = { {10,20}, {30,200}, {400,50}, {30,20} };\n        System.out.println(twoCitySchedCost(costs)); \n    }\n}\n\n    <\/code><\/pre>\n    <\/div>\n\n    <div class=\"wp_blog_code-tab-content\" data-lang=\"cpp\">\n      <pre><code class=\"language-cpp\">\n#include &lt;bits\/stdc++.h&gt;\nusing namespace std;\n\nint twoCitySchedCost(vector<vector<int>>& costs) {\n    int m = costs.size();\n    int n = m \/ 2;\n    \/\/ sort descending by (cost[1] - cost[0])\n    sort(costs.begin(), costs.end(), [](const vector<int>& a, const vector<int>& b) {\n        return (a[1] - a[0]) > (b[1] - b[0]);\n    });\n\n    int ans = 0;\n    for (int i = 0; i < n; ++i) ans += costs[i][0];\n    for (int i = n; i < m; ++i) ans += costs[i][1];\n    return ans;\n}\n\nint main() {\n    vector<vector<int>> costs = {{10,20},{30,200},{400,50},{30,20}};\n    cout << twoCitySchedCost(costs) << endl; \/\/ expected 110 (based on original logic)\n    return 0;\n}\n\n<\/code><\/pre>\n    <\/div>\n\n    <div class=\"wp_blog_code-tab-content\" data-lang=\"c\">\n      <pre><code class=\"language-c\">\n#include &lt;stdio.h&gt;\n#include &lt;stdlib.h&gt;\n\ntypedef struct { int c0, c1; } Pair;\nint cmp(const void *pa, const void *pb) {\n    const Pair *a = (const Pair*)pa;\n    const Pair *b = (const Pair*)pb;\n    int da = a->c1 - a->c0;\n    int db = b->c1 - b->c0;\n    \/\/ mimic JS comparator (b.diff - a.diff) -> sort descending by diff\n    return db - da;\n}\nint twoCitySchedCost(Pair *arr, int len) {\n    qsort(arr, len, sizeof(Pair), cmp);\n    int n = len \/ 2;\n    int ans = 0;\n    for (int i = 0; i < n; ++i) ans += arr[i].c0;\n    for (int i = n; i < len; ++i) ans += arr[i].c1;\n    return ans;\n}\n\nint main() {\n    Pair costs[] = {{10,20},{30,200},{400,50},{30,20}};\n    int len = sizeof(costs)\/sizeof(costs[0]);\n    printf(\"%d\\n\", twoCitySchedCost(costs, len)); \/\/ prints result\n    return 0;\n}\n\n      <\/code><\/pre>\n    <\/div>\n\n    <div class=\"wp_blog_code-tab-content\" data-lang=\"cs\">\n      <pre><code class=\"language-csharp\">\nusing System;\n\nclass Program {\n    static int TwoCitySchedCost(int[][] costs) {\n        Array.Sort(costs, (x, y) => (y[1] - y[0]) - (x[1] - x[0])); \/\/ descending by diff\n        int n = costs.Length \/ 2;\n        int ans = 0;\n        for (int i = 0; i < n; i++) ans += costs[i][0];\n        for (int i = n; i < costs.Length; i++) ans += costs[i][1];\n        return ans;\n    }\n\n    static void Main() {\n        int[][] costs = new int[][] {\n            new int[] {10, 20},\n            new int[] {30, 200},\n            new int[] {400, 50},\n            new int[] {30, 20}\n        };\n        Console.WriteLine(TwoCitySchedCost(costs)); \/\/ prints result\n    }\n}\n\n      <\/code><\/pre>\n    <\/div>\n  <\/div>\n<\/div>\n\n<script>\ndocument.addEventListener(\"DOMContentLoaded\", () => {\n  const buttons = document.querySelectorAll(\".wp_blog_code-tab-button\");\n  const contents = document.querySelectorAll(\".wp_blog_code-tab-content\");\n\n  buttons.forEach((button) => {\n    button.addEventListener(\"click\", () => {\n      const lang = button.getAttribute(\"data-lang\");\n\n      buttons.forEach((btn) => btn.classList.remove(\"active\"));\n      contents.forEach((content) => content.classList.remove(\"active\"));\n\n      button.classList.add(\"active\");\n      document\n        .querySelector(`.wp_blog_code-tab-content[data-lang=\"${lang}\"]`)\n        .classList.add(\"active\");\n    });\n  });\n\n  const themeToggle = document.getElementById(\"blogNotesThemeToggle\");\n  const themeContainer = document.querySelector(\".wp_blog_theme\");\n\n  themeToggle.addEventListener(\"click\", () => {\n    themeContainer.classList.toggle(\"dark-mode\");\n    themeToggle.textContent =\n      themeContainer.classList.contains(\"dark-mode\") ? \"\u2600\ufe0f\" : \"\ud83c\udf19\";\n  });\n});\n<\/script>\n\n","protected":false},"excerpt":{"rendered":"<p>\ud83c\udf19 Problem Statement: A company is planning to interview 2n people. Given the array costs where costs[i] = [aCosti, bCosti], the cost of flying the ith person to city a is aCosti, and the cost of flying the ith person to city b is bCosti. Return the minimum cost to fly every person to a<\/p>\n","protected":false},"author":108,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"om_disable_all_campaigns":false,"_monsterinsights_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0,"footnotes":""},"categories":[210,322,176,175,211,811,810,174,172,173],"tags":[],"class_list":{"0":"post-10059","1":"post","2":"type-post","3":"status-publish","4":"format-standard","6":"category-algorithms","7":"category-algorithms-and-data-structures","8":"category-csharp","9":"category-cplusplus","10":"category-data-structures","11":"category-data-structures-and-algorithms","12":"category-dsa","13":"category-java","14":"category-javascript","15":"category-python"},"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts\/10059","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/users\/108"}],"replies":[{"embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/comments?post=10059"}],"version-history":[{"count":1,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts\/10059\/revisions"}],"predecessor-version":[{"id":10060,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts\/10059\/revisions\/10060"}],"wp:attachment":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/media?parent=10059"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/categories?post=10059"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/tags?post=10059"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}