From e6b4390e6ef4e30d66ad47fe98f5c45e329db79e Mon Sep 17 00:00:00 2001 From: ivan Date: Fri, 28 Feb 2025 04:20:50 -0600 Subject: [PATCH] longest common prefix --- .../longest_common_prefix.py | 21 ++++++++++++++++ .../test_longest_common_prefix_round_14.py | 24 +++++++++++++++++++ 2 files changed, 45 insertions(+) create mode 100644 src/my_project/interviews/top_150_questions_round_14/longest_common_prefix.py create mode 100644 tests/test_150_questions_round_14/test_longest_common_prefix_round_14.py diff --git a/src/my_project/interviews/top_150_questions_round_14/longest_common_prefix.py b/src/my_project/interviews/top_150_questions_round_14/longest_common_prefix.py new file mode 100644 index 00000000..cd1afe61 --- /dev/null +++ b/src/my_project/interviews/top_150_questions_round_14/longest_common_prefix.py @@ -0,0 +1,21 @@ +from typing import List, Union, Collection, Mapping, Optional +from abc import ABC, abstractmethod + +class Solution: + def longestCommonPrefix(self, strs: List[str]) -> str: + + if not strs: + return '' + else: + min_strs, max_strs = min(strs), max(strs) + count = 0 + + len_min_strs = len(min_strs) + + for i in range(len_min_strs): + if min_strs[i] != max_strs[i]: + break + else: + count += 1 + + return min_strs[:count] \ No newline at end of file diff --git a/tests/test_150_questions_round_14/test_longest_common_prefix_round_14.py b/tests/test_150_questions_round_14/test_longest_common_prefix_round_14.py new file mode 100644 index 00000000..7e7900fc --- /dev/null +++ b/tests/test_150_questions_round_14/test_longest_common_prefix_round_14.py @@ -0,0 +1,24 @@ +import unittest +from src.my_project.interviews.top_150_questions_round_14\ +.longest_common_prefix import Solution + + +class LongestCommonPrefixTestCase(unittest.TestCase): + + def test_longest_common_prefix(self): + solution = Solution() + output = solution.longestCommonPrefix(strs=["flower","flow","flight"]) + target = 'fl' + self.assertEqual(target, output) + + def test_longest_no_common_prefix(self): + solution = Solution() + output = solution.longestCommonPrefix(strs=["dog","racecar","car"]) + target = '' + self.assertEqual(target, output) + + def test_longest_common_prefix_null_list(self): + solution = Solution() + output = solution.longestCommonPrefix(strs=[]) + target = '' + self.assertEqual(target, output) \ No newline at end of file