34. Word Count
Difficulty: Medium · Topics: Arrays, Aggregations, Strings, Filtering & Selection
The classic Spark example. lines has a text column of space-separated words.
Count how often each word appears, ignoring case (lower-case everything). Return word, cnt ordered by cnt descending, then word ascending.
Row order matters for this problem. Your code is graded on 3 test cases, including hidden edge cases.
Sample data
lines
| id | text |
|---|---|
| 1 | Spark is fast |
| 2 | spark is fun |
| 3 | PySpark is Spark |
Expected output
| word | cnt |
|---|---|
| is | 3 |
| spark | 3 |
| fast | 1 |
| fun | 1 |
| pyspark | 1 |
Hints
Hint 1
F.split(F.lower("text"), " ") produces an array column.Hint 2
F.explode(...) turns each array element into its own row.Hint 3
Group by the exploded word and count.Learn the concepts
- explode · 4 min read. Turn each array element into its own row, and the rows explode silently drops.
- String functions · 5 min read. concat vs concat_ws, substring, split, trim and padding, with the null traps in each.
- groupBy + agg · 4 min read. Aggregate rows per group: counts, sums, averages, and how count(*) differs from count(col).
PySpark functions you'll practise
- groupBy
- agg
- count
- explode
- split
- select
- orderBy
- lower
Related problems
- Learning Path per Student · Medium · Arrays, Aggregations, Strings, Filtering & Selection
- Sorted Distinct Purchase List · Medium · Arrays, Aggregations
- Item Positions in a Basket (POSEXPLODE) · Medium · Arrays, Filtering & Selection
- Keep Users with No Interests (EXPLODE_OUTER) · Medium · Arrays, Filtering & Selection
- How Much Does Each Query Read? · Medium · Data Lake, Joins, Aggregations
Browse
Topics: Window Functions · Joins · Aggregations · Pivot, Unpivot & Rollup · Arrays · Null Handling · Conditional Logic · Dates · Filtering & Selection · Strings · Data Lake · Lakehouse · Streaming · Data Prep for AI · Spark Performance
Difficulty: Easy · Medium · Hard · Learn · All problems · dbt practice