Doctor's Orders: Catching DIAB1 Patients! 😷💉
IntuitionWe need to filter patients whose conditions contain at least one word that starts with "DIAB1". Since "conditions" is a space-separated string of diffe
# **Intuition**  

We need to filter patients whose **conditions** contain at least one word that **starts with** `"DIAB1"`. Since `"conditions"` is a space-separated string of different illnesses, we can't directly check for `"DIAB1"` as a substring. Instead, we must ensure that `"DIAB1"` appears as a **separate word**, not as part of another condition like `"DIAB201"`.  

For example:  
✅ `"DIAB100 MYOP"` → **Valid** (contains `"DIAB100"`)  
✅ `"ACNE DIAB100"` → **Valid** (contains `"DIAB100"`)  
❌ `"DIAB201"` → **Invalid** (`DIAB2` does not match `DIAB1`)  
❌ `"ACNE +DIAB100"` → **Invalid** (`+DIAB100` is not a separate word)  



# **Approach**  
1. **Use Regular Expressions (`regex`) to find words that start with `"DIAB1"`**  
   - We need to ensure that `"DIAB1"` is a standalone word. A simple `.str.contains('DIAB1')` would also match `"DIAB1000"` or `"DIAB201"`, which is incorrect.  
   - To fix this, we use `(^|\s)DIAB1\d*($|\s)`, which ensures:
     - `"DIAB1"` appears **at the start (`^`) or after a space (`\s`)**  
     - It is **followed by a number (`\d*`), a space (`\s`), or the end of the string (`$`)**  
   - This prevents false matches with `"DIAB201"` or `"SOMEDIAB100"`.

2. **Apply the regex filter using `.str.contains()`**
   - `patients['conditions'].str.contains(r'(^|\s)DIAB1\d*($|\s)', na=False)`  
   - This checks if any row in `"conditions"` contains a valid `"DIAB1"` condition.  
   - `na=False` ensures that missing values (`NaN`) are treated as `False`, avoiding errors.

3. **Return the filtered DataFrame**  
   - The rows where `"conditions"` match our regex are selected and returned.  



# **Complexity**  
- **Time Complexity:** **O(n)**  
  - We iterate through **n rows** and apply a regex match for each row.  
  - Regex `.str.contains()` runs in **O(m)** time per row (where `m` is the string length), but since medical conditions are short, it approximates to **O(1)** per row.  
  - Overall, it scales linearly with **O(n)**.

- **Space Complexity:** **O(1)**  
  - We do **not** use extra data structures.  
  - We filter the DataFrame **in place**, so memory usage is constant.  
  

🚀 Upvote if this helped! It keeps me motivated to post more solutions!

![images.png](https://assets.leetcode.com/users/images/f0ab5afd-1554-4700-ae42-0373d36dd0b2_1740830928.9827623.png)




```python
import pandas as pd

def find_patients(patients: pd.DataFrame) -> pd.DataFrame:
    return patients[patients['conditions'].str.contains(r'(^|\s)DIAB1\d*($|\s)', na=False)]
```

['Pandas']