Growth ๐ŸŒณ/Practice ๐Ÿ’ป

[LeetCode] 602. Friend Requests II: Who Has the Most Friends

์ธ” 2023. 5. 12. 16:08

๐Ÿ“ข ๋ณธ ํฌ์ŠคํŒ…์— ํ™œ์šฉ๋˜๋Š” ๊ธฐ๋ณธ ๋ฌธ์ œ ๋ฐ ์ž๋ฃŒ ์ถœ์ฒ˜๋Š”

       ๋ฆฌํŠธ์ฝ”๋“œ Problems, https://leetcode.com/problemset/all/์ž„์„ ๋ฐํž™๋‹ˆ๋‹ค.


โœ” ๋ฌธ์ œ

https://leetcode.com/problems/friend-requests-ii-who-has-the-most-friends/description/

 

Friend Requests II: Who Has the Most Friends - LeetCode

Can you solve this real interview question? Friend Requests II: Who Has the Most Friends - Table: RequestAccepted +----------------+---------+ | Column Name | Type | +----------------+---------+ | requester_id | int | | accepter_id | int | | accept_date |

leetcode.com

Table : RequestAccepted

Write an SQL query to find the people who have the most friends and the most friends number.

The test cases are generated so that only one person has the most friends.

The query result format is in the following example.

 

Example 1: 


โœ” ํ’€์ด

  ๋ฌธ์ œ ์š”๊ตฌ์‚ฌํ•ญ  

 

์นœ๊ตฌ๊ฐ€ ๊ฐ€์žฅ ๋งŽ์€ ์‚ฌ๋žŒ์˜ id์™€ ์นœ๊ตฌ ์ˆ˜๋ฅผ ์ถœ๋ ฅํ•ด์•ผ ํ•œ๋‹ค.

๋‹จ ์˜ˆ์‹œ๋ฅผ ๋ณด๋ฉด requester ๊ธฐ์ค€์œผ๋กœ accepter ๊ฐ€ ์นœ๊ตฌ ๊ด€๊ณ„๊ฐ€ ๋˜์ง€๋งŒ

request ํ•œ ์ ์ด ์—†์–ด๋„ accepter๊ฐ€ ๋˜๋ฉด requester์™€ ์นœ๊ตฌ ๊ด€๊ณ„๋กœ ๋ณด๋Š” ๊ฒƒ์ด ์ค‘์š”ํ•˜๋‹ค.

๋”ฐ๋ผ์„œ ๋‹จ์ˆœํ•˜๊ฒŒ accepter๋ฅผ requester๋กœ ๋ณผ ์ˆ˜ ์žˆ๋„๋ก ์ปฌ๋Ÿผ์„ ๋’ค์ง‘์–ด์„œ ์ˆ˜ํ‰ ๊ฒฐํ•ฉํ•ด์ฃผ๊ธฐ ์œ„ํ•ด UNION ALL์„ ์‚ฌ์šฉํ–ˆ๋‹ค.

๊ฒฐํ•ฉ ํ…Œ์ด๋ธ”์— ๋Œ€ํ•ด์„œ requester_id ์ปฌ๋Ÿผ์„ ๊ธฐ์ค€์œผ๋กœ ์—ฐ๊ฒฐ ๊ด€๊ณ„๋ฅผ ์ง‘๊ณ„ํ•˜๋ฉด,

๊ฒฐ๊ณผ์ ์œผ๋กœ requester ↔ accepter ๋ฐฉํ–ฅ ๊ด€๊ณ„์—†์ด id๋ณ„๋กœ ์นœ๊ตฌ ๊ด€๊ณ„๋ฅผ ์ง‘๊ณ„ํ•  ์ˆ˜ ์žˆ๋‹ค.

SELECT requester_id AS id,
COUNT(accepter_id) AS num
 FROM (
    SELECT requester_id, accepter_id
    FROM RequestAccepted

    UNION ALL

    SELECT accepter_id, requester_id 
    FROM RequestAccepted
 ) T1
 GROUP BY 1
 ORDER BY 2 DESC
 LIMIT 1

 

 

 

'Growth ๐ŸŒณ > Practice ๐Ÿ’ป' ์นดํ…Œ๊ณ ๋ฆฌ์˜ ๋‹ค๋ฅธ ๊ธ€

[LeetCode] 1045. Customers Who Bought All Products  (0) 2023.05.18
[LeetCode] 608. Tree Node  (0) 2023.05.16
[LeetCode] 601. Human Traffic of Stadium  (0) 2023.05.11
[LeetCode] 577. Employee Bonus  (0) 2023.05.10
[LeetCode] 585. Investments in 2016  (0) 2023.05.09