diff --git a/Arrays & Strings/Duplicates checking cpp b/Arrays & Strings/Duplicates checking cpp new file mode 100644 index 0000000..bce13b2 --- /dev/null +++ b/Arrays & Strings/Duplicates checking cpp @@ -0,0 +1,13 @@ +class Solution { +public: + bool containsDuplicate(vector& nums) { + sort(nums.begin(), nums.end()); // O(n log n) + for (int i = 1; i < nums.size(); ++i) { + if (nums[i] == nums[i - 1]) { + return true; + } + } + return false; + } +}; + diff --git a/Problems/#14 - Longest Common Prefix - Easy/explanation.md b/Problems/#14 - Longest Common Prefix - Easy/explanation.md new file mode 100644 index 0000000..cd3cf33 --- /dev/null +++ b/Problems/#14 - Longest Common Prefix - Easy/explanation.md @@ -0,0 +1,22 @@ +# Leetcode Problem #14: Longest Common Prefix (Easy) + +## Problem + +Given an array of strings `strs`, return the **longest common prefix** string amongst them. +If there is no common prefix, return an **empty string**. + +--- + +## Approach + +- Start with the first string as the **initial prefix**. +- Compare it with the next string: + - If the current string doesn't start with the prefix, **trim the prefix** by one character from the end. + - Repeat until it matches or becomes an empty string. +- Continue this for all strings in the list. + +--- + + + + diff --git a/Problems/#14 - Longest Common Prefix - Easy/solution.cpp b/Problems/#14 - Longest Common Prefix - Easy/solution.cpp new file mode 100644 index 0000000..a6cff60 --- /dev/null +++ b/Problems/#14 - Longest Common Prefix - Easy/solution.cpp @@ -0,0 +1,27 @@ +// LeetCode #14 - Longest Common Prefix +// Language: C++ + +#include +#include + +using namespace std; + +class Solution { +public: + string longestCommonPrefix(vector& strs) { + if (strs.empty()) return ""; + + string prefix = strs[0]; + + for (int i = 1; i < strs.size(); ++i) { + int j = 0; + while (j < prefix.size() && j < strs[i].size() && prefix[j] == strs[i][j]) + ++j; + prefix = prefix.substr(0, j); + if (prefix.empty()) return ""; + } + + return prefix; + } +}; +