Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 0 additions & 26 deletions String/299. Bulls and Cows.py

This file was deleted.

Empty file.
26 changes: 26 additions & 0 deletions problems/medium/bulls_and_cows_299/solution.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
# Tags: String, Hash Table, Counting
from collections import Counter


class Solution:
def get_hint(self, secret: str, guess: str) -> str:
"""
Time complexity: O(n), where n is the length of secret/guess.
We traverse the strings once to count bulls and build counters,
then iterate through at most 10 digits (0-9) to count cows.

Space complexity: O(1), counters store at most 10 digits (0-9).
"""
bulls = 0
cows = 0
s_count = Counter()
g_count = Counter()
for s, g in zip(secret, guess):
if s == g:
bulls += 1
else:
s_count[s] += 1
g_count[g] += 1
for digit in s_count:
cows += min(s_count[digit], g_count[digit])
return f"{bulls}A{cows}B"
14 changes: 14 additions & 0 deletions problems/medium/bulls_and_cows_299/test_solution.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import pytest
from .solution import Solution
from tests.base_test import BaseTestSolution


class TestSolution(BaseTestSolution):
solution = Solution()

@pytest.mark.parametrize("method_name, secret, guess, expected, timeout", [
('get_hint', "1807", "7810", "1A3B", BaseTestSolution.DEFAULT_TIMEOUT),
('get_hint', "1123", "0111", "1A1B", BaseTestSolution.DEFAULT_TIMEOUT),
])
def test_get_hint(self, method_name, secret, guess, expected, timeout):
self._run_test(self.solution, method_name, (secret, guess,), expected, timeout)
Loading