K Most Frequent Strings
Given an array of strings strs and an integer k, return the k most frequent strings.
Return the answer **sorted by frequency from highest to lowest**. When two strings have the **same frequency**, order them **lexicographically** (alphabetical, ascending) — so the result is fully deterministic.
For example, with strs = ["go", "coding", "byte", "byte", "go", "interview", "go"] and k = 2, the counts are go: 3, byte: 2, and coding/interview once each. The two most frequent are ["go", "byte"].
Example cases
- two most frequentin strs = ["go","coding","byte","byte","go","interview","go"], k = 2out ["go","byte"]go appears 3 times, byte twice; both beat the single-count strings.
- tie broken lexicographicallyin strs = ["i","love","code","i","love","you"], k = 2out ["i","love"]i and love each appear twice; code/you once. Among the ties i < love alphabetically.
- all tiedin strs = ["b","a","c"], k = 2out ["a","b"]All count 1, so the two lexicographically smallest win: a then b.
Constraints
- 1 <= strs.length <= 10^4
- 1 <= strs[i].length <= 20
- strs[i] consists of lowercase English letters.
- 1 <= k <= the number of distinct strings in strs.
strs =
["go","coding","byte","byte","go","interview","go"]
k =
2