Count Occurrences in Text — LeetCode 2738 Python Solution

MediumLeetCode PremiumDatabase
Problem
#2738
Reading time
3 min

Table schema

SQL
Table: Files +-------------+---------+ | Column Name | Type | +-- ----------+---------+ | file_name | varchar | | content | text | +-------------+---------+ file_name is the column with unique values of this table. Each row contains file_name and the content of that file.

Example

SQL
+-------------+---------+
| Column Name | Type    |
+-- ----------+---------+
| file_name   | varchar |
| content     | text    |
+-------------+---------+
file_name is the column with unique values of this table. 
Each row contains file_name and the content of that file.

Python solution

Python
import duckdb
import pandas as pd

# Pass input tables as keyword arguments matching the SQL table names.
def solution(**tables) -> pd.DataFrame:
    con = duckdb.connect()
    for name, df in tables.items():
        con.register(name, df)
    return con.execute("""SELECT 'bull' AS word, COUNT(*) AS count
FROM Files
WHERE content LIKE '% bull %'
UNION
SELECT 'bear' AS word, COUNT(*) AS count
FROM Files
WHERE content LIKE '% bear %';""").df()

Complexity

MeasureComplexity
TimeO(n log n) (typical)
SpaceO(n) auxiliary

Related problems

Frequently asked questions

How hard is LeetCode 2738. Count Occurrences in Text?
LeetCode 2738. Count Occurrences in Text is rated Medium on LeetCode.
What topics does LeetCode 2738. Count Occurrences in Text cover?
LeetCode 2738. Count Occurrences in Text is tagged Database on LeetCode.
Is LeetCode 2738. Count Occurrences in Text a premium problem?
Yes. LeetCode 2738. Count Occurrences in Text is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview