Skip to content

Prepare For Coder Interview – Denny

  • Basic
  • Medium
  • Hard
  • Architect
  • Life

LeetCode: Find Median Given Frequency of Numbers

Posted on March 16, 2018July 26, 2020 by braindenny

Find Median Given Frequency of Numbers



Similar Problems:

  • Median Employee Salary
  • CheatSheet: Leetcode For Code Interview
  • CheatSheet: Common Code Problems & Follow-ups
  • Tag: getmedian, #sql

The Numbers table keeps the value of number and its frequency.

+----------+-------------+
|  Number  |  Frequency  |
+----------+-------------|
|  0       |  7          |
|  1       |  1          |
|  2       |  3          |
|  3       |  1          |
+----------+-------------+

In this table, the numbers are 0, 0, 0, 0, 0, 0, 0, 1, 2, 2, 2, 3, so the median is (0 + 0) / 2 = 0.

+--------+
| median |
+--------|
| 0.0000 |
+--------+

Write a query to find the median of all numbers and name the result as median.

Github: code.dennyzhang.com

Credits To: leetcode.com

Leave me comments, if you have better ways to solve.


## https://code.dennyzhang.com/find-median-given-frequency-of-numbers
select avg(t3.Number) as median
from Numbers as t3 
inner join 
    (select t1.Number, 
        abs(sum(case when t1.Number>t2.Number then t2.Frequency else 0 end) -
            sum(case when t1.Number<t2.Number then t2.Frequency else 0 end)) as count_diff
    from numbers as t1, numbers as t2
    group by t1.Number) as t4
on t3.Number = t4.Number
where t3.Frequency>=t4.count_diff
linkedin
github
slack

Post Views: 10
Posted in HardTagged getmedian, sql

Post navigation

LeetCode: Find Cumulative Salary of an Employee
LeetCode: Find Duplicate Subtrees

Leave a Reply Cancel reply

Your email address will not be published.

Tags

#array #backtracking #bfs #binarytree #bitmanipulation #blog #classic #codetemplate #combination #dfs #dynamicprogramming #game #graph #greedy #heap #inspiring #interval #linkedlist #manydetails #math #palindrome #recursive #slidingwindow #stack #string #subarray #trie #twopointer #twosum binarysearch editdistance hashmap intervaldp knapsack monotone oodesign presum rectangle redo review rotatelist series sql treetraversal unionfind

Recent Posts

  • a
  • a
  • a
  • a
  • a

Recent Comments

    Archives

    Categories

    • Amusing
    • Basic
    • Easy
    • Hard
    • Life
    • Medium
    • Resource
    • Review
    • Series
    • Uncategorized
    Proudly powered by WordPress | Theme: petals by Aurorum.