question_slug
stringlengths
3
77
title
stringlengths
1
183
slug
stringlengths
12
45
summary
stringlengths
1
160
author
stringlengths
2
30
certification
stringclasses
2 values
created_at
stringdate
2013-10-25 17:32:12
2025-04-12 09:38:24
updated_at
stringdate
2013-10-25 17:32:12
2025-04-12 09:38:24
hit_count
int64
0
10.6M
has_video
bool
2 classes
content
stringlengths
4
576k
upvotes
int64
0
11.5k
downvotes
int64
0
358
tags
stringlengths
2
193
comments
int64
0
2.56k
determine-if-two-strings-are-close
✅🤖| Full explanation with plenty of languages | 95.38% beaten | 🤖
full-explanation-with-plenty-of-language-osrs
Intuition\nThe goal of the problem is to determine if two strings, word1 and word2, are considered "close" based on certain operations. The allowed operations a
makarkananov
NORMAL
2024-01-14T11:57:18.576298+00:00
2024-01-14T12:02:04.102572+00:00
419
false
## Intuition\nThe goal of the problem is to determine if two strings, `word1` and `word2`, are considered "close" based on certain operations. The allowed operations are swapping any two existing characters and transforming every occurrence of one existing character into another existing character, and vice versa. \n\nTo solve this, we need to check if the two words have the same set of characters and if the frequencies of these characters are permutations of each other.\n\n---\n## Approach\nThe approach involves several steps:\n\n1. Check if the lengths of `word1` and `word2` are equal. If not, they cannot be considered close, and the function returns false.\n\n2. Create two arrays, `letters1` and `letters2`, each of size 26, to represent the frequency of each letter in the corresponding word. These arrays are initialized to zero.\n\n3. Iterate through each character in `word1` and `word2`, updating the respective frequency arrays using ASCII values. The ASCII trick involves subtracting the ASCII value of \'a\' (97) from the ASCII value of the current letter to get a zero-based index.\n\n4. Check if `word1` and `word2` consist of the same set of letters. This is done by comparing whether each letter is present in one word but not the other. If the condition is met for any letter, the function returns false.\n\n5. Sort both frequency arrays in ascending order.\n\n6. Check if the sorted frequency arrays are equal, confirming that the frequencies of letters are permutations of each other.\n\n7. If all conditions are satisfied, return `true`, otherwise return `false`.\n\n---\n## Complexity\n- Time complexity: **O(n)** - The function iterates through the characters of word1 and word2, and the sorting step takes constant time.\n\n- Space complexity: **O(1)** - Two arrays of size 26 are used to store the frequency of letters for each word.\n\n---\n## "Talk is cheap. Show me the code." - Linus Torvalds\n``` C++ []\n#include <algorithm>\n#include <vector>\n\nclass Solution {\npublic:\n bool closeStrings(std::string word1, std::string word2) {\n if (word1.length() != word2.length()) {\n return false;\n }\n\n std::vector<int> letters1(26, 0); // counter of letters for word1\n std::vector<int> letters2(26, 0); // counter of letters for word2\n\n for (char letter : word1) { // counting letters in word1 using ASCII tables trick\n letters1[letter - \'a\'] += 1;\n }\n\n for (char letter : word2) { // counting letters in word2 using ASCII tables trick\n letters2[letter - \'a\'] += 1;\n }\n\n for (int i = 0; i < letters1.size(); i++) { // checking if word1 & word2 consist of the same letters\n if ((letters1[i] > 0) != (letters2[i] > 0)) {\n return false;\n }\n }\n\n // checking if counters are just permutations of each other\n std::sort(letters1.begin(), letters1.end()); // sorting them\n std::sort(letters2.begin(), letters2.end());\n \n for (int i = 0; i < letters1.size(); i++) { // checking if they are equal\n if (letters1[i] != letters2[i]) {\n return false;\n }\n }\n\n return true;\n }\n};\n\n```\n``` Go []\nfunc closeStrings(word1 string, word2 string) bool {\n if len(word1) != len(word2) { // lengths of words must be equal\n return false\n }\n\n letters1 := make([]int, 26) // counter of letters for word1\n letters2 := make([]int, 26) // counter of letters for word2\n\n for _, letter := range word1 { // counting letters in word1 using ascii tables trick\n letters1[int(letter) - 97] += 1\n }\n for _, letter := range word2 { // counting letters in word2 using ascii tables trick\n letters2[int(letter) - 97] += 1\n }\n\n for i := 0; i < len(letters1); i++ { // checking if word1 & word2 consist of same letters\n if (letters1[i] > 0) != (letters2[i] > 0) {\n return false\n }\n }\n \n // checking if counters are just permutations of each other\n sort.Ints(letters1) // sorting them\n sort.Ints(letters2)\n for i := 0; i < len(letters1); i++ { // checking if they are equal\n if letters1[i] != letters2[i] {\n return false\n }\n }\n\n return true\n}\n```\n``` Python []\nclass Solution:\n def closeStrings(self, word1: str, word2: str) -> bool:\n if len(word1) != len(word2):\n return False\n\n letters1 = [0] * 26 # counter of letters for word1\n letters2 = [0] * 26 # counter of letters for word2\n\n for letter in word1: # counting letters in word1 using ASCII tables trick\n letters1[ord(letter) - ord(\'a\')] += 1\n\n for letter in word2: # counting letters in word2 using ASCII tables trick\n letters2[ord(letter) - ord(\'a\')] += 1\n\n # checking if word1 & word2 consist of the same letters\n for i in range(len(letters1)):\n if (letters1[i] > 0) != (letters2[i] > 0):\n return False\n\n # checking if counters are just permutations of each other\n letters1.sort() # sorting them\n letters2.sort()\n\n for i in range(len(letters1)): # checking if they are equal\n if letters1[i] != letters2[i]:\n return False\n\n return True\n\n```\n``` Javascript []\n/**\n * @param {string} word1\n * @param {string} word2\n * @return {boolean}\n */\nvar closeStrings = function(word1, word2) {\n if (word1.length !== word2.length) {\n return false;\n }\n\n const letters1 = new Array(26).fill(0); // counter of letters for word1\n const letters2 = new Array(26).fill(0); // counter of letters for word2\n\n for (const letter of word1) { // counting letters in word1 using ASCII tables trick\n letters1[letter.charCodeAt(0) - \'a\'.charCodeAt(0)] += 1;\n }\n\n for (const letter of word2) { // counting letters in word2 using ASCII tables trick\n letters2[letter.charCodeAt(0) - \'a\'.charCodeAt(0)] += 1;\n }\n\n // checking if word1 & word2 consist of the same letters\n for (let i = 0; i < letters1.length; i++) {\n if ((letters1[i] > 0) !== (letters2[i] > 0)) {\n return false;\n }\n }\n\n // checking if counters are just permutations of each other\n letters1.sort(); // sorting them\n letters2.sort();\n\n for (let i = 0; i < letters1.length; i++) { // checking if they are equal\n if (letters1[i] !== letters2[i]) {\n return false;\n }\n }\n\n return true;\n};\n```\n``` C# []\npublic class Solution {\n public bool CloseStrings(string word1, string word2) {\n if (word1.Length != word2.Length) {\n return false;\n }\n\n int[] letters1 = new int[26]; // counter of letters for word1\n int[] letters2 = new int[26]; // counter of letters for word2\n\n foreach (char letter in word1) { // counting letters in word1 using ASCII tables trick\n letters1[letter - \'a\'] += 1;\n }\n\n foreach (char letter in word2) { // counting letters in word2 using ASCII tables trick\n letters2[letter - \'a\'] += 1;\n }\n\n // checking if word1 & word2 consist of the same letters\n for (int i = 0; i < letters1.Length; i++) {\n if ((letters1[i] > 0) != (letters2[i] > 0)) {\n return false;\n }\n }\n\n // checking if counters are just permutations of each other\n Array.Sort(letters1); // sorting them\n Array.Sort(letters2);\n\n for (int i = 0; i < letters1.Length; i++) { // checking if they are equal\n if (letters1[i] != letters2[i]) {\n return false;\n }\n }\n\n return true;\n }\n}\n\n```\n``` Rust []\nimpl Solution {\n pub fn close_strings(word1: String, word2: String) -> bool {\n if word1.len() != word2.len() {\n return false;\n }\n\n let mut letters1 = vec![0; 26]; // counter of letters for word1\n let mut letters2 = vec![0; 26]; // counter of letters for word2\n\n for letter in word1.chars() { // counting letters in word1 using ASCII tables trick\n letters1[(letter as u8 - b\'a\') as usize] += 1;\n }\n\n for letter in word2.chars() { // counting letters in word2 using ASCII tables trick\n letters2[(letter as u8 - b\'a\') as usize] += 1;\n }\n\n // checking if word1 & word2 consist of the same letters\n for i in 0..letters1.len() {\n if (letters1[i] > 0) != (letters2[i] > 0) {\n return false;\n }\n }\n\n // checking if counters are just permutations of each other\n letters1.sort(); // sorting them\n letters2.sort();\n\n for i in 0..letters1.len() { // checking if they are equal\n if letters1[i] != letters2[i] {\n return false;\n }\n }\n\n true\n }\n}\n```\n``` Java []\nclass Solution {\n public boolean closeStrings(String word1, String word2) {\n if (word1.length() != word2.length()) {\n return false;\n }\n\n int[] letters1 = new int[26]; // counter of letters for word1\n int[] letters2 = new int[26]; // counter of letters for word2\n\n for (char letter : word1.toCharArray()) { // counting letters in word1 using ASCII tables trick\n letters1[letter - \'a\'] += 1;\n }\n\n for (char letter : word2.toCharArray()) { // counting letters in word2 using ASCII tables trick\n letters2[letter - \'a\'] += 1;\n }\n\n // checking if word1 & word2 consist of the same letters\n for (int i = 0; i < letters1.length; i++) {\n if ((letters1[i] > 0) != (letters2[i] > 0)) {\n return false;\n }\n }\n\n // checking if counters are just permutations of each other\n Arrays.sort(letters1); // sorting them\n Arrays.sort(letters2);\n\n for (int i = 0; i < letters1.length; i++) { // checking if they are equal\n if (letters1[i] != letters2[i]) {\n return false;\n }\n }\n\n return true;\n }\n}\n```\n``` Ruby []\n# @param {String} word1\n# @param {String} word2\n# @return {Boolean}\ndef close_strings(word1, word2)\n return false if word1.length != word2.length\n\n letters1 = Array.new(26, 0) # counter of letters for word1\n letters2 = Array.new(26, 0) # counter of letters for word2\n\n word1.each_char do |letter| # counting letters in word1 using ASCII tables trick\n letters1[letter.ord - \'a\'.ord] += 1\n end\n\n word2.each_char do |letter| # counting letters in word2 using ASCII tables trick\n letters2[letter.ord - \'a\'.ord] += 1\n end\n\n # checking if word1 & word2 consist of the same letters\n (0...letters1.length).each do |i|\n return false if (letters1[i] > 0) != (letters2[i] > 0)\n end\n\n # checking if counters are just permutations of each other\n letters1.sort! # sorting them\n letters2.sort!\n\n (0...letters1.length).each do |i| # checking if they are equal\n return false if letters1[i] != letters2[i]\n end\n\n true\nend\n\n```\n---\n## Results\n![image.png](https://assets.leetcode.com/users/images/5077740e-fad2-419e-8370-105db2d62a35_1705232351.225031.png)\n\n---\n## Do not forget to upvote \uD83D\uDE0F\n![image.png](https://assets.leetcode.com/users/images/3b01ce41-89d9-44c6-a41e-2d5f58df587b_1705233171.2301803.png)\n\n\n
4
0
['String', 'Python', 'C++', 'Java', 'Go', 'Python3', 'Rust', 'Ruby', 'JavaScript', 'C#']
1
determine-if-two-strings-are-close
Python3 *oneliner* linear solution O(n)
python3-oneliner-linear-solution-on-by-s-agsd
Intuition\n Describe your first thoughts on how to solve this problem. \nWhen tackling this problem, we need to focus on two key aspects:\n\n1) Character Flexib
sio13
NORMAL
2024-01-14T11:46:00.201246+00:00
2024-01-14T11:46:00.201278+00:00
145
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWhen tackling this problem, we need to focus on two key aspects:\n\n1) **Character Flexibility**: The problem allows for swapping elements, suggesting that the specific order of characters in the strings is irrelevant. This flexibility means we can consider each string as if it were sorted alphabetically. It simplifies our mental model, as we are not concerned with the sequence of operations required to achieve this sorted state.\n\n2) **Count Exchangeability**: The problem also allows us to exchange the frequency of any two groups of characters. Therefore, the ratio of character counts isn\'t crucial. For example, the strings "aabbb" and "aaabb" are equivalent in this context because they can be transformed into one another through character exchanges. \n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nTo solve this problem, we need to ensure two conditions are met:\n\n- **Identical Character Sets**: Both strings must consist of the same set of characters. This condition is necessary to ensure that one string can be rearranged into the other. We can efficiently compare character sets by constructing and comparing two sets in O(n) time. An optimization is possible using a boolean array of length 26 (for each lowercase letter), marking true for each character present.\n\n- **Matching Character Counts**: For both strings, while the exact frequency of each character does not need to match, the overall distribution of frequencies should be identical when sorted. We can use a hashmap (like Python\'s Counter) to tally the occurrences of each character in O(n) time. We then compare the sorted counts of both strings. Since we\'re dealing with a finite set of characters (26 lowercase letters), the sorting can be considered as having a constant time complexity.\n\nThe solution returns True if both the character sets and their relative counts match; otherwise, it returns False.\n\n# Complexity\n- Time Complexity: O(n). The primary operations (constructing sets, counting characters, and sorting counts) depend linearly on the length of the input strings.\n\n- Space Complexity: O(1). The space used is constant, as it\'s only dependent on the fixed size of the character set (26 lowercase letters). We use a set and a hashmap for each string, but their sizes are bounded by the size of the alphabet, not the length of the input strings.\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nfrom collections import Counter\n\nclass Solution:\n def closeStrings(self, word1: str, word2: str) -> bool:\n return set(word1) == set(word2) and sorted(Counter(word1).values()) == sorted(Counter(word2).values())\n \n```
4
0
['Python3']
0
determine-if-two-strings-are-close
Easy and Explained || Beats 100% || [Java/C++/Python/JavaScript]
easy-and-explained-beats-100-javacpython-lhfm
Intuition\n1. Operation 1 allows you to freely reorder the string.\n2. Operation 2 allows you to freely reassign the letters\' frequencies.\n3. That means every
Shivansu_7
NORMAL
2024-01-14T07:08:35.791104+00:00
2024-01-14T07:08:35.791139+00:00
131
false
# Intuition\n1. Operation 1 allows you to freely reorder the string.\n2. Operation 2 allows you to freely reassign the letters\' frequencies.\n3. That means every unique characters should have the same frequency in both the string.\n\n# Approach\n1. Counting Character Frequencies:\n - The code uses two integer arrays (char1 and char2) of size 26 to represent the frequencies of characters in the input strings word1 and word2. The assumption is that the characters are lowercase English letters (\'a\' to \'z\'). The frequencies are updated based on the occurrence of each character in the respective strings.\n2. Checking Conditions for Close Strings:\n - The first condition checks that all unique characters present in word1 should be available in word2 and vice versa, without considering their frequency. If this condition is not satisfied (i.e., if there is a character present in one string but not in the other), the function returns false.\n3. Sorting and Comparing Frequencies:\n - If the first condition is satisfied, the frequencies of characters in both strings are sorted. The function then returns true if the sorted frequency arrays are equal (using Arrays.equals), indicating that the strings are "close strings" based on the defined conditions.\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(1)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```java []\nclass Solution {\n public boolean closeStrings(String word1, String word2) {\n // Two conditions required for satisfying a close string:\n // *1. All UNIQUE characters present in String 1 should be available in String 2 & vice versa.(NOT CONSIDERING THEIR FREQUENCY).\n\n // If condition 1 is satisfied then a Sorted Frequency Arr of One String should be same as the Sorted Frequency Arr of Other.\n // If both Conditions are true then its a closeString.*\n\n int char1[] = new int[26];\n int char2[] = new int[26];\n for(char ch: word1.toCharArray()){\n char1[ch-\'a\']++;\n }\n for(char ch: word2.toCharArray()){\n char2[ch-\'a\']++;\n }\n for(int i=0; i<26; i++){\n if((char1[i]==0 && char2[i]!=0)|| (char1[i]!=0 && char2[i]==0)){\n return false;\n }\n }\n Arrays.sort(char1);\n Arrays.sort(char2);\n\n return Arrays.equals(char1,char2);\n \n }\n}\n```\n```C++ []\nclass Solution {\npublic:\n bool closeStrings(string word1, string word2) {\n // Two conditions required for satisfying a close string:\n // 1. All UNIQUE characters present in String 1 should be available in String 2 & vice versa. (NOT CONSIDERING THEIR FREQUENCY).\n\n // If condition 1 is satisfied, then a Sorted Frequency Arr of One String should be the same as the Sorted Frequency Arr of the Other.\n // If both Conditions are true, then it\'s a closeString.\n\n int char1[26];\n int char2[26];\n\n memset(char1, 0, sizeof(char1));\n memset(char2, 0, sizeof(char2));\n\n for (char ch : word1) {\n char1[ch - \'a\']++;\n }\n\n for (char ch : word2) {\n char2[ch - \'a\']++;\n }\n\n for (int i = 0; i < 26; i++) {\n if ((char1[i] == 0 && char2[i] != 0) || (char1[i] != 0 && char2[i] == 0)) {\n return false;\n }\n }\n\n sort(char1, char1 + 26);\n sort(char2, char2 + 26);\n\n for (int i = 0; i < 26; i++) {\n if (char1[i] != char2[i]) {\n return false;\n }\n }\n\n return true;\n }\n};\n```\n```Python3 []\nclass Solution:\n def closeStrings(self, word1: str, word2: str) -> bool:\n # Two conditions required for satisfying a close string:\n # 1. All UNIQUE characters present in String 1 should be available in String 2 & vice versa. (NOT CONSIDERING THEIR FREQUENCY).\n\n # If condition 1 is satisfied, then a Sorted Frequency Arr of One String should be the same as the Sorted Frequency Arr of the Other.\n # If both Conditions are true, then it\'s a closeString.\n\n char1 = [0] * 26\n char2 = [0] * 26\n\n for ch in word1:\n char1[ord(ch) - ord(\'a\')] += 1\n\n for ch in word2:\n char2[ord(ch) - ord(\'a\')] += 1\n\n for i in range(26):\n if (char1[i] == 0 and char2[i] != 0) or (char1[i] != 0 and char2[i] == 0):\n return False\n\n char1.sort()\n char2.sort()\n\n return char1 == char2\n\n```\n```JavaScript []\n/**\n * @param {string} word1\n * @param {string} word2\n * @return {boolean}\n */\nvar closeStrings = function(word1, word2) {\n // Two conditions required for satisfying a close string:\n // 1. All UNIQUE characters present in String 1 should be available in String 2 & vice versa. (NOT CONSIDERING THEIR FREQUENCY).\n\n // If condition 1 is satisfied, then a Sorted Frequency Arr of One String should be the same as the Sorted Frequency Arr of the Other.\n // If both Conditions are true, then it\'s a closeString.\n\n let char1 = new Array(26).fill(0);\n let char2 = new Array(26).fill(0);\n\n for (let ch of word1) {\n char1[ch.charCodeAt(0) - \'a\'.charCodeAt(0)]++;\n }\n\n for (let ch of word2) {\n char2[ch.charCodeAt(0) - \'a\'.charCodeAt(0)]++;\n }\n\n for (let i = 0; i < 26; i++) {\n if ((char1[i] === 0 && char2[i] !== 0) || (char1[i] !== 0 && char2[i] === 0)) {\n return false;\n }\n }\n\n char1.sort((a, b) => a - b);\n char2.sort((a, b) => a - b);\n\n return JSON.stringify(char1) === JSON.stringify(char2);\n};\n\n// Example usage:\n// let result = closeStrings("abc", "bca");\n// console.log(result);\n```
4
0
['C++', 'Java', 'Python3', 'JavaScript']
1
determine-if-two-strings-are-close
JAVA Solution Explained in HINDI
java-solution-explained-in-hindi-by-the_-vqmb
https://youtu.be/59KfskW5S8A\n\nFor explanation, please watch the above video and do like, share and subscribe the channel. \u2764\uFE0F\n\nSubscribe link:- htt
The_elite
NORMAL
2024-01-14T05:30:06.697427+00:00
2024-01-14T05:30:06.697453+00:00
625
false
https://youtu.be/59KfskW5S8A\n\nFor explanation, please watch the above video and do like, share and subscribe the channel. \u2764\uFE0F\n\nSubscribe link:- https://youtube.com/@quantumCode7?si=NzjWYmiCbqfFBUJE\n\nSubscribe Goal:- 100\nCurrent Subscriber:- 57\n\n# Code\n```\nclass Solution {\n public boolean closeStrings(String word1, String word2) {\n \n int fqarr1[] = new int[26];\n int fqarr2[] = new int[26];\n\n for(char c : word1.toCharArray()) {\n fqarr1[c - \'a\']++;\n }\n\n for(char c : word2.toCharArray()) {\n fqarr2[c - \'a\']++;\n }\n\n for(int i = 0; i < 26; i++) {\n if((fqarr1[i] == 0 && fqarr2[i] != 0) || (fqarr1[i] != 0 && fqarr2[i] == 0)) {\n return false;\n }\n }\n\n Arrays.sort(fqarr1);\n Arrays.sort(fqarr2);\n\n for(int i = 0; i < 26; i++) {\n if(fqarr1[i] != fqarr2[i]) {\n return false;\n }\n }\n return true;\n\n }\n}\n```
4
0
['Java']
0
determine-if-two-strings-are-close
Faster than 98.3% || Simple C++ Solution || Time/Space : O(n)/O(1)
faster-than-983-simple-c-solution-timesp-8cky
Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(1)\n\n# Code\n\nclass Solution {\npublic:\n bool closeStrings(string w1, string w2) {\n
abhijeet5000kumar
NORMAL
2024-01-14T04:53:08.158032+00:00
2024-01-14T04:54:42.645830+00:00
159
false
# Complexity\n- Time complexity:\n$$O(n)$$\n\n- Space complexity:\n$$O(1)$$\n\n# Code\n```\nclass Solution {\npublic:\n bool closeStrings(string w1, string w2) {\n if(w1.size()!=w2.size()) return false;\n vector<int> freq1(26,0),freq2(26,0);\n for(auto it:w1) freq1[it-\'a\']++;\n for(auto it:w2) freq2[it-\'a\']++;\n for(int i=0;i<26;i++){\n if((freq1[i]>0 && freq2[i]==0) || (freq1[i]==0 && freq2[i]>0)) return false;\n }\n sort(freq1.begin(),freq1.end());\n sort(freq2.begin(),freq2.end());\n return freq1==freq2;\n }\n};\n```
4
0
['Array', 'String', 'Sorting', 'Counting', 'C++']
0
determine-if-two-strings-are-close
[ Python ] | Simple & Clean Code | Using Counter
python-simple-clean-code-using-counter-b-6jav
Code\n\nclass Solution:\n def closeStrings(self, s1: str, s2: str) -> bool:\n return set(s1) == set(s2) and Counter(Counter(s1).values()) == Counter(C
yash_visavadia
NORMAL
2023-04-24T01:40:16.437309+00:00
2023-04-24T01:40:16.437359+00:00
523
false
# Code\n```\nclass Solution:\n def closeStrings(self, s1: str, s2: str) -> bool:\n return set(s1) == set(s2) and Counter(Counter(s1).values()) == Counter(Counter(s2).values())\n\n```
4
0
['String', 'Python3']
0
determine-if-two-strings-are-close
Very easy C++ solution
very-easy-c-solution-by-chetanchaudhary-i8nu
Intuition\n Describe your first thoughts on how to solve this problem. \n\nIn order to be close , the length of word1 , word2 should be equal.\nif this conditio
chetanchaudhary
NORMAL
2022-12-22T13:13:42.165988+00:00
2022-12-22T13:13:42.166035+00:00
142
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\nIn order to be close , the length of word1 , word2 should be equal.\nif this condition dont match simply return false.\n\nOperation 1 allows you to freely reorder the string.\nSo we will store the characters present in word1 , word2 . \nif any character present in word1 is not present in word2 or vice versa we would simply return false . \n\nif operation1 satisfies , we would move to operation 2\n\n\nOperation 2 allows you to freely reassign the letters frequencies.\nSo we will store the frequencies of chars . Since we can resassign letter frequencies , we now simply need to check if all the frequencies of word1 matches with frequencies of word2.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. if length of word1 is not equal to word 2 return false \n2. Use a vector of size 26 say m1 and store the frequency of the character in vector m1 for word1 .\n\npoition of a -> 0 b-1 ... z -> 25\n\n3. Now iterate through word2 , and check if character of word2 exists in m1 . If not return false ;and update m2 vector for storing frequencies of characters of word2 .\n\n4. Now sort vector v1 and v2 ;\n\n5. iterate and check frequencies if they dont match return false ;\n\nwe will understand it using example now .\n\nword1 = nibbbi\n\nword2 = niibbi\n\nchars in word1 -> n , i , b \n\nchars in word2 -> n , i , b \n\nsince all the characters of word1 and word2 match , \n\nwe will check frequencies \n\nword1 = n -> 1 , i-> 2 , b-> 3 \nword2 = n-> 1 , i -> 3 , b -> 2 \n\nsince frequencies are stored in vectors and vectors are sorted . we will match frequencies. if frequencies dont match , simply return false \n\n\n\n\n\n\n# Complexity\n- Time complexity: 0(nlogn) n is 26 here \n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n\n- Space complexity: 0(26) ~ 0(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n bool closeStrings(string word1, string word2) {\n\n if(word1.length() != word2.length())\n return false ; \n\n vector<int> m1(26) , m2(26) ; \n\n for(char ch : word1)\n m1[ch - \'a\']++;\n\n for(char ch : word2)\n {\n int val = m1[ch - \'a\'];\n \n if(val == 0)\n return false ;\n\n m2[ch - \'a\']++;\n\n }\n\n sort(m1.begin() , m1.end());\n sort(m2.begin() , m2.end());\n\n for(int i = 0 ; i < 26 ; i++)\n {\n if(m1[i] != m2[i] )\n return false ;\n }\n return true ; \n }\n};\n```
4
0
['C++']
0
determine-if-two-strings-are-close
C++ || C# easy solutions.
c-c-easy-solutions-by-aloneguy-jgjk
Explanation of the Solutions!\n\n 1. Check if lengths match \uD83D\uDCDD\n If the lengths of word1 and word2 are not equal, return false right away, s
aloneguy
NORMAL
2022-12-02T16:35:10.373821+00:00
2024-10-12T16:27:34.391623+00:00
47
false
# Explanation of the Solutions!\n\n 1. Check if lengths match \uD83D\uDCDD\n If the lengths of word1 and word2 are not equal, return false right away, since no operations can make strings of different lengths equivalent.\n\n 2. Count occurrences of each character \uD83D\uDD22\n You create two maps, occurences_1 and occurences_2, to store how many times each character appears in word1 and word2.\n\n 3.Check if character sets match \uD83D\uDD0D\n If any character in word1 doesn\u2019t exist in word2, you return false. This ensures both strings contain the same set of characters, just possibly arranged differently.\n\n 4.Compare frequency distributions \uD83D\uDCCA\n Instead of directly comparing the occurrence counts, you compare the frequency distributions. You check if the number of characters with the same frequency is the same in both words by using to_freq_1 and to_freq_2. If they match, return true, otherwise return false.\n\n```C++ []\nclass Solution {\npublic:\n bool closeStrings(string word1, string word2) {\n if (word1.length() != word2.length())\n return false;\n \n unordered_map<char, int> occurences_1;\n unordered_map<char, int> occurences_2;\n unordered_map<char, int> to_freq_1;\n unordered_map<char, int> to_freq_2;\n \n for (auto i = 0; i < word1.length(); ++i) {\n occurences_1[word1[i]]++;\n occurences_2[word2[i]]++;\n }\n\n for (auto pair : occurences_1) {\n if (occurences_2[pair.first] == 0)\n return false;\n\n to_freq_1[pair.second] ++;\n }\n\n for (auto pair : occurences_2) \n to_freq_2[pair.second] ++;\n\n for (auto pair :to_freq_1) {\n if (to_freq_2[pair.first] != pair.second)\n return false;\n }\n\n return true;\n }\n};\n```\n```C# []\npublic class Solution {\n public bool CloseStrings(string word1, string word2) {\n if (word1.Length != word2.Length)\n return false; \n \n int[] count1 = new int[26]; \n int[] count2 = new int[26]; \n int[] freq1 = new int[26]; \n int[] freq2 = new int[26]; \n \n // Count character occurrences in both words\n foreach (char c in word1)\n count1[c - \'a\']++;\n foreach (char c in word2)\n count2[c - \'a\']++;\n \n // Check if both words have the same set of characters\n for (int i = 0; i < 26; i++) {\n if ((count1[i] == 0 && count2[i] != 0) || (count1[i] != 0 && count2[i] == 0))\n return false; \n }\n \n // Count the frequency of frequencies\n foreach (int count in count1)\n if (count > 0) freq1[count]++;\n foreach (int count in count2)\n if (count > 0) freq2[count]++;\n \n // Compare frequency distributions\n for (int i = 0; i < 26; i++) {\n if (freq1[i] != freq2[i])\n return false; \n }\n \n return true; \n }\n}\n```\n
4
0
['String', 'C++', 'C#']
0
determine-if-two-strings-are-close
Java Most Simplest Solution
java-most-simplest-solution-by-janhvi__2-dp3b
\nclass Solution {\n public boolean closeStrings(String word1, String word2) {\n int[]str1 = new int[26];\n int[]str2 = new int[26];\n f
Janhvi__28
NORMAL
2022-12-02T15:29:08.368245+00:00
2022-12-02T15:29:08.368291+00:00
272
false
```\nclass Solution {\n public boolean closeStrings(String word1, String word2) {\n int[]str1 = new int[26];\n int[]str2 = new int[26];\n for(char c: word1.toCharArray())\n str1[c - \'a\']++;\n for(char c: word2.toCharArray()){\n str2[c - \'a\']++;\n if(str1[c -\'a\']==0)\n return false;\n }\n Arrays.sort(str1);\n Arrays.sort(str2);\n for(int i=0; i<26; i++){\n if (str1[i]!= str2[i])\n return false;\n }\n return true;\n }\n}\n```
4
0
['Java']
0
determine-if-two-strings-are-close
Easy||Explained in Detailed
easyexplained-in-detailed-by-kalashpatil-ygmu
\nclass Solution {\npublic:\n bool closeStrings(string word1, string word2) {\n unordered_map<char,int> mp1; //A map to get the frequency of string 1\
kalashpatil
NORMAL
2022-12-02T07:31:42.576358+00:00
2022-12-02T07:31:42.576389+00:00
1,459
false
```\nclass Solution {\npublic:\n bool closeStrings(string word1, string word2) {\n unordered_map<char,int> mp1; //A map to get the frequency of string 1\n unordered_map<char,int> mp2; //A map to get the frequency of string 2\n vector<int> v1;\n vector<int> v2;\n if(word1.size()==word2.size()) //It is possible only if both string have same length\n {\n for(auto it:word1)\n {\n mp1[it]++; \n }\n for(auto it:word2)\n {\n mp2[it]++;\n }\n for(int i=0;i<word2.size();i++)\n {\n if (word2.find(word1[i]) != std::string::npos) //To check whether the element exist in the string 2 or not\n {\n v1.push_back(mp1[word1[i]]);//if it exist just addedits frequency to a new vector\n }\n else\n {\n return false;//If it doesnot exist then return false.\n }\n if (word1.find(word2[i]) != std::string::npos) //same for string 2 elements in string 1\n {\n v2.push_back(mp2[word2[i]]);\n }\n else\n {\n return false;\n }\n }\n sort(v1.begin(),v1.end()); //sorted the vectors \n sort(v2.begin(),v2.end());\n if(v1==v2) //compared them so that if the occurences are matching then return true else false\n return true;\n else\n return false;\n }\n else\n return false;\n }\n};\n//Suggestions and feedbacks are welcomed. Happy Coding!!\n```
4
0
['String', 'C']
0
determine-if-two-strings-are-close
C++ || O(1) Time O(N) Space || Clean and Concise Code
c-o1-time-on-space-clean-and-concise-cod-qxwr
\n\n# Complexity\n- Time complexity: O(N)\n Add your time complexity here, e.g. O(n) \n\n- Space complexity: O(26 + 26) = O(1)\n Add your space complexity here,
ashay028
NORMAL
2022-12-02T07:26:25.221664+00:00
2022-12-02T07:28:31.065173+00:00
62
false
\n\n# Complexity\n- Time complexity: O(N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(26 + 26) = O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n bool closeStrings(string word1, string word2) {\n vector<int> f1(26) , f2(26);\n for(auto &it : word1) ++f1[it-\'a\'];\n for(auto &it : word2)\n {\n if(f1[it-\'a\']==0) return false; //If we dont have this letter in word1\n ++f2[it-\'a\'];\n } \n sort(f1.begin(),f1.end());\n sort(f2.begin(),f2.end());\n return f1==f2;\n }\n};\n```
4
0
['C++']
0
determine-if-two-strings-are-close
C++ || HashMap || Simple Approach
c-hashmap-simple-approach-by-monk_man-nf70
\n# Approach\n Describe your approach to solving the problem. \nUsing HashMap and Vector\n# Complexity\n- Time complexity: O(n)\n Add your time complexity here
monk_man
NORMAL
2022-12-02T06:42:04.237404+00:00
2022-12-02T06:42:04.237439+00:00
761
false
\n# Approach\n<!-- Describe your approach to solving the problem. -->\nUsing HashMap and Vector\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n bool closeStrings(string word1, string word2) {\n if(word1.size()!=word2.size())\n {\n return false;\n }\n \n map<char,int>mp1;\n map<char,int>mp2;\n string a1="",a2="";\n for(int i=0;i<word1.size();i++)\n {\n mp1[word1[i]]++;\n mp2[word2[i]]++;\n\n }\n vector<int>p1,p2;\n for(auto it1:mp1)\n {\n a1+=it1.first;\n p1.push_back(it1.second);\n } \n \n for(auto it2:mp2)\n {\n a2+=it2.first;\n p2.push_back(it2.second) ; \n } \n \n sort(p1.begin(),p1.end());\n sort(p2.begin(),p2.end());\n\n for(int i=0;i<p1.size();i++)\n {\n if(p1[i]!=p2[i])\n {\n return false;\n }\n }\n\n if( a1!=a2)\n {\n return false;\n }\n \n return true;\n\n }\n};\n```
4
0
['Hash Table', 'C++']
1
determine-if-two-strings-are-close
C++ || Easy Sol. Faster Than 97.1% || TC : O(n) || Space : O(1)
c-easy-sol-faster-than-971-tc-on-space-o-3j8n
Complexity\n- Time complexity : O(n) , where n is word length\n\n- Space complexity : O(1)\n\n# Code\n\nclass Solution {\npublic:\n bool closeStrings(string
Khwaja_Abdul_Samad
NORMAL
2022-12-02T06:32:01.926161+00:00
2022-12-02T07:14:39.916338+00:00
215
false
# Complexity\n- Time complexity : O(n) , where n is word length\n\n- Space complexity : O(1)\n\n# Code\n```\nclass Solution {\npublic:\n bool closeStrings(string word1, string word2) {\n \n if(word1.length() != word2.length())\n return false ;\n\n vector<int> f1(26 , 0) , f2(26 , 0);\n \n //Store The Count of Each Letter from both words separately \n for(int i = 0 ; i<word1.length() ; i++)\n {\n f1[word1[i]-\'a\']++;\n f2[word2[i]-\'a\']++;\n }\n\n //Check For wheather a letter is present in one word and absent in \n // another word , then return false\n // Because we can\'t interchange that letter with any other word\n // ex : abcdef abcde will always return false\n\n for(int i = 0 ; i<26 ; i++)\n {\n if (f1[i] == 0 ^ f2[i] == 0)\n return false;\n }\n \n // Now Sort The frequencies \n sort(f1.begin() , f1.end());\n sort(f2.begin() , f2.end());\n \n // If they don\'t match return false\n for(int i = 0 ; i<26 ; i++)\n {\n if(f1[i] != f2[i])\n return false;\n }\n \n return true;\n\n\n }\n};\n```
4
0
['C++']
0
determine-if-two-strings-are-close
80% javascript really easy to understand solution
80-javascript-really-easy-to-understand-izlz2
Visit my youtube! Thank you!\nhttps://www.youtube.com/channel/UCkhEaNAOO8tig5NHqqxXIeg\n\n\nvar closeStrings = function(word1, word2) {\n if(word1.length !=
rlawnsqja850
NORMAL
2022-12-02T03:05:47.937249+00:00
2023-01-09T04:28:08.332310+00:00
528
false
Visit my youtube! Thank you!\nhttps://www.youtube.com/channel/UCkhEaNAOO8tig5NHqqxXIeg\n\n```\nvar closeStrings = function(word1, word2) {\n if(word1.length != word2.length) return false;\n \n let oneMap = {}\n let twoMap = {}\n \n for(let i= 0; i<word1.length;i++){\n oneMap[word1[i]] = oneMap[word1[i]] ? oneMap[word1[i]]+1 :1;\n twoMap[word2[i]] = twoMap[word2[i]] ? twoMap[word2[i]]+1 :1;\n }\n let arr =Object.values(twoMap);\n for(let i in oneMap){\n if(!twoMap[i]) return false;\n let index = arr.indexOf(oneMap[i])\n if(index ==-1) return false;\n arr.splice(index,1)\n }\n\n return arr.length == 0\n\n};\n```
4
0
['JavaScript']
0
determine-if-two-strings-are-close
Clear and Concise cpp code - O(N)
clear-and-concise-cpp-code-on-by-bhavya_-9zix
Complexity\n- Time complexity: O(N)\n\n- Space complexity: O(N)\n\n# Code\n\nclass Solution {\npublic:\n bool closeStrings(string word1, string word2) {\n
bhavya_kawatra13
NORMAL
2022-12-02T02:03:34.040950+00:00
2022-12-02T19:16:46.330942+00:00
384
false
# Complexity\n- Time complexity: O(N)\n\n- Space complexity: O(N)\n\n# Code\n```\nclass Solution {\npublic:\n bool closeStrings(string word1, string word2) {\n vector<int>m(26,0),m1(26,0);\n for(auto i:word1)m[i-\'a\']++;\n for(auto i:word2)m1[i-\'a\']++;\n for(int i=0;i<26;i++){\n if((m[i]&&!m1[i])||(!m[i]&&m[i]))return false; // if a character exist only in one string then return false..\n }\n sort(m.begin(),m.end());\n sort(m1.begin(),m1.end());\n return m==m1;\n\n }\n};\n```
4
0
['Sorting', 'C++']
1
determine-if-two-strings-are-close
go easy
go-easy-by-61kg-tq6y
Runtime: 55 ms, faster than 50.00% of Go online submissions for Determine if Two Strings Are Close.\nMemory Usage: 7 MB, less than 100.00% of Go online submissi
61kg
NORMAL
2022-12-02T01:41:01.250357+00:00
2022-12-02T01:41:01.250385+00:00
293
false
Runtime: 55 ms, faster than 50.00% of Go online submissions for Determine if Two Strings Are Close.\nMemory Usage: 7 MB, less than 100.00% of Go online submissions for Determine if Two Strings Are Close.\n\n```\nfunc closeStrings(word1 string, word2 string) bool {\n if len(word1) != len(word2) {\n return false\n }\n countW1, countW2 := make([]int,26),make([]int,26) \n existW1, existW2 := [26]bool{},[26]bool{}\n \n for i := range word1 {\n countW1[word1[i] - \'a\']++\n countW2[word2[i] - \'a\']++\n existW1[word1[i] - \'a\'] = true\n existW2[word2[i] - \'a\'] = true\n }\n \n sort.Ints(countW1)\n sort.Ints(countW2)\n w1 := [26]int{}\n w2 := [26]int{}\n copy(w1[:],countW1)\n copy(w2[:],countW2)\n return w1 == w2 && existW1 == existW2 \n}\n```
4
0
['Go']
1
determine-if-two-strings-are-close
JS frequency mapping + explanation O(n) O(1)
js-frequency-mapping-explanation-on-o1-b-ln8e
Intuition\nRule 1 means that the ordering of the letters is irrelevant.\nRule 2 means that the overall population of occurences has to be the same, but doesn\'t
crankyinmv
NORMAL
2022-12-02T01:02:04.651953+00:00
2022-12-02T01:02:04.651991+00:00
377
false
## Intuition\nRule 1 means that the ordering of the letters is irrelevant.\nRule 2 means that the overall population of occurences has to be the same, but doesn\'t have to map to the same letters.\n\nFor example `latter` has 4 letters (aler) occuring 1 time, and 1 (t) occuring 2 times. `taller` also has 4 letters (taer) occuring 1 time and 1 (l) occuring 4 times. These 2 strings are close.\n\nJust be sure that all the letters from the first word occur at least once in the second word, and vice versa.\n\n## Approach\n\n- Frequency map both strings (we\'re interested in counts of letters here).\n- Verify that no letter occurs in just 1 string.\n- Sort the frequency mappings.\n- Verify that the mappings are the same.\n\n## Complexity\n- Time complexity: $O(n)$\n\n- Space complexity: $O(1)$\n\nKeep in mind that this involves sorting, but the arrays sorted are a fixed length of 26.\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n## Code\n```\n/**\n * @param {string} word1\n * @param {string} word2\n * @return {boolean}\n */\nvar closeStrings = function(word1, word2) \n{\n const A = \'a\'.charCodeAt(0);\n let map1 = Array(26).fill(0), map2 = Array(26).fill(0);\n\n for(let i=0; i<word1.length; i++)\n map1[word1.charCodeAt(i)-A]++;\n for(let i=0; i<word2.length; i++)\n map2[word2.charCodeAt(i)-A]++;\n\n for(let i=0; i<26; i++)\n if((map1[i] === 0 && map2[i] !== 0) || (map2[i] === 0 && map1[i] !== 0))\n return false;\n\n map1.sort((a,b)=>b-a);\n map2.sort((a,b)=>b-a);\n\n for(let i=0; i<26; i++)\n {\n if(map1[i] !== map2[i])\n return false;\n if(map1[i] === 0)\n break;\n }\n\n return true; \n};\n```
4
0
['JavaScript']
1
determine-if-two-strings-are-close
Need Only Map for Optimization as well as for easy understanding
need-only-map-for-optimization-as-well-a-l2yg
\nclass Solution {\n\tpublic boolean closeStrings(String word1, String word2) {\n\t\tHashMap<Character, Integer> map1 = new HashMap<>();\n\t\tfor (int i = 0; i
Aditya_jain_2584550188
NORMAL
2022-07-15T05:37:41.838144+00:00
2022-07-15T05:37:41.838207+00:00
207
false
```\nclass Solution {\n\tpublic boolean closeStrings(String word1, String word2) {\n\t\tHashMap<Character, Integer> map1 = new HashMap<>();\n\t\tfor (int i = 0; i < word1.length(); i++) {\n\t\t\tmap1.put(word1.charAt(i), map1.getOrDefault(word1.charAt(i), 0) + 1);\n\t\t}\n\n\t\tHashMap<Character, Integer> map2 = new HashMap<>();\n\t\tfor (int i = 0; i < word2.length(); i++) {\n\t\t\tmap2.put(word2.charAt(i), map2.getOrDefault(word2.charAt(i), 0) + 1);\n\t\t}\n\t\tif (!map1.keySet().equals(map2.keySet())) {\n\t\t\treturn false;\n\t\t}\n\t\tArrayList<Integer> list1 = new ArrayList<>();\n\t\tlist1.addAll(map1.values());\n\n\t\tArrayList<Integer> list2 = new ArrayList<>();\n\t\tlist2.addAll(map2.values());\n\n\t\tCollections.sort(list1);\n\t\tCollections.sort(list2);\n\n\n\t\tif (list1.size() != list2.size()) {\n\t\t\treturn false;\n\t\t}\n\t\tint i = 0;\n\t\tint j = 0;\n\t\twhile (i < list1.size() && j < list2.size()) {\n\t\t\tif (list1.get(i) !=list2.get(j)) {\n // System.out.println(list1.get(i)+" "+list2.get(i));\n\t\t\t\treturn false;\n\t\t\t} else {\n\t\t\t\ti++;\n\t\t\t\tj++;\n\t\t\t}\n\t\t}\n\t\treturn true;\n\t}\n}\n```
4
0
['Java']
0
determine-if-two-strings-are-close
Python Simplest Approach in One Line! Easy & Short, faster than 90%
python-simplest-approach-in-one-line-eas-z7br
So Simple - Faster than 90%\n\nclass Solution:\n def closeStrings(self, word1: str, word2: str) -> bool:\n w1 = Counter(word1)\n w2 = Counter(w
yehudisk
NORMAL
2021-01-22T09:42:09.790161+00:00
2021-01-22T09:59:09.272785+00:00
334
false
**So Simple - Faster than 90%**\n```\nclass Solution:\n def closeStrings(self, word1: str, word2: str) -> bool:\n w1 = Counter(word1)\n w2 = Counter(word2)\n \n letters1 = [x for x in w1.keys()]\n letters2 = [x for x in w2.keys()]\n \n freq1 = [x for x in w1.values()]\n freq2 = [x for x in w2.values()]\n\n return sorted(letters1) == sorted(letters2) and sorted(freq1) == sorted(freq2)\n```\n**Same idea in one line - a bit slower**\n```\nclass Solution:\n def closeStrings(self, word1: str, word2: str) -> bool:\n return sorted([x for x in Counter(word1).keys()]) == sorted([x for x in Counter(word2).keys()]) and sorted([x for x in Counter(word1).values()]) == sorted([x for x in Counter(word2).values()])\n```\n**Like it? please upvote...**
4
0
['Python']
1
determine-if-two-strings-are-close
C# Simple counting O(N)
c-simple-counting-on-by-leoooooo-cy3j
\npublic class Solution {\n public bool CloseStrings(string word1, string word2) {\n if(word1.Length != word2.Length) return false;\n int[] a =
leoooooo
NORMAL
2020-11-15T05:21:46.791455+00:00
2020-11-15T05:21:46.791493+00:00
167
false
```\npublic class Solution {\n public bool CloseStrings(string word1, string word2) {\n if(word1.Length != word2.Length) return false;\n int[] a = new int[26];\n int[] b = new int[26];\n int maxLen = 0;\n for(int i = 0; i < word1.Length; i++)\n {\n maxLen = Math.Max(maxLen, ++a[word1[i] - \'a\']);\n maxLen = Math.Max(maxLen, ++b[word2[i] - \'a\']);\n }\n int[] len = new int[maxLen+1];\n for(int i = 0; i < a.Length; i++)\n {\n if (a[i] > 0 && b[i] == 0) return false;\n if (b[i] > 0 && a[i] == 0) return false;\n len[a[i]]++;\n len[b[i]]--;\n }\n \n return len.All(x => x == 0);\n }\n}\n```
4
0
[]
0
determine-if-two-strings-are-close
[Javascript] HashMap
javascript-hashmap-by-alanchanghsnu-8zhf
Check whether two chars counting number hashMaps are same.\nEx1: abb vs baa\n->{a:1, b: 2} vs {a:2, b:1}\n-> {1:1, 2:1} vs {1:1, 2:1} -> true\n\nEx2: cabbba vs
alanchanghsnu
NORMAL
2020-11-15T04:04:37.257414+00:00
2020-11-15T04:09:51.364563+00:00
959
false
Check whether two chars counting number hashMaps are same.\nEx1: `abb` vs `baa`\n->`{a:1, b: 2}` vs `{a:2, b:1}`\n-> `{1:1, 2:1}` vs `{1:1, 2:1}` -> true\n\nEx2: `cabbba` vs `abbccc`\n-> `{a:2, b:3, c:1}` vs `{a:1, b:2, c:3}`\n-> `{1:1, 2:1, 3:1}` vs `{1:1, 2:1, 3:1}` -> true\n\n```\nvar closeStrings = function(word1, word2) {\n if (word1.length !== word2.length) return false;\n \n const chars = new Array(26).fill(0),\n used = new Array(26).fill(false),\n a = \'a\'.charCodeAt(0);\n \n for (let i = 0; i < word1.length; i++) {\n chars[word1.charCodeAt(i)-a]++;\n used[word1.charCodeAt(i)-a] = true;\n }\n \n let countMap = {};\n \n for (let n of chars) {\n if (countMap[n] === undefined)\n countMap[n] = 0;\n countMap[n]++;\n }\n \n chars.fill(0);\n for (let i = 0; i < word2.length; i++) {\n if (!used[word2.charCodeAt(i)-a]) // if there is new char not used in word1, return false\n return false;\n chars[word2.charCodeAt(i)-a]++;\n }\n \n for (let n of chars) {\n if (countMap[n] === undefined) // if one char has the frequency unused in word1, return false\n return false;\n countMap[n]--;\n if (countMap[n] < 0)\n return false;\n }\n \n return true;\n};
4
0
['JavaScript']
1
determine-if-two-strings-are-close
Java 20 lines O(n) Solution
java-20-lines-on-solution-by-abhinavkuma-zvfo
\nclass Solution {\n public boolean closeStrings(String word1, String word2) {\n \n int freq1[] = new int[26];\n int freq2[] = new int[2
abhinavkumar08
NORMAL
2020-11-15T04:01:53.036819+00:00
2020-11-16T02:39:00.222439+00:00
774
false
```\nclass Solution {\n public boolean closeStrings(String word1, String word2) {\n \n int freq1[] = new int[26];\n int freq2[] = new int[26];\n int []visited1 = new int[26];\n int []visited2 = new int[26];\n \n for(char ch : word1.toCharArray()){\n freq1[ch-\'a\']++;\n visited1[ch-\'a\'] = 1;\n }\n \n for(char ch : word2.toCharArray()){\n freq2[ch-\'a\']++;\n visited2[ch-\'a\'] = 1;\n }\n Arrays.sort(freq1);\n Arrays.sort(freq2);\n return Arrays.equals(visited1, visited2) && Arrays.equals(freq1, freq2);\n }\n}\n\n```
4
0
['Java']
1
determine-if-two-strings-are-close
Easiesest solution - will make you count this as easy problem
easiesest-solution-will-make-you-count-t-xijn
Approachif the length of both words or the set of both words don't match no way to match the close string. if you pass both the case just get a counter of word
ayushuh
NORMAL
2025-01-13T18:14:56.675296+00:00
2025-01-13T18:14:56.675296+00:00
578
false
# Approach <!-- Describe your approach to solving the problem. --> if the length of both words or the set of both words don't match no way to match the close string. if you pass both the case just get a counter of word and compare the sorted order if it does not match return false else true. # Complexity - Time complexity: O(n) <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: O(1) <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```python3 [] from collections import Counter class Solution: def closeStrings(self, word1: str, word2: str) -> bool: if (len(word1) != len(word2)) or (set(word1) != set(word2)): return False fr1 = Counter(word1) fr2 = Counter(word2) if sorted(fr1.values()) != sorted(fr2.values()): return False return True ```
3
0
['Python3']
1
determine-if-two-strings-are-close
Frequency Count and Meta-Frequency Matching
frequency-count-and-meta-frequency-match-janp
IntuitionThe strings can be made identical if they have the same set of characters, and the frequency of these characters can be rearranged to match.ApproachCou
lucifer_debug
NORMAL
2024-12-20T09:16:16.277425+00:00
2024-12-20T09:16:16.277425+00:00
153
false
# Intuition The strings can be made identical if they have the same set of characters, and the frequency of these characters can be rearranged to match. # Approach Count character frequencies for both strings using arrays mp1 and mp2. Verify that both strings use the same set of characters. Create meta-frequency arrays (mp11 and mp22) to track how often each frequency appears. Compare the meta-frequency arrays; if they match, return true. # Complexity - Time complexity: O(n) - Space complexity: 𝑂(n1) # Code ```cpp [] class Solution { public: bool closeStrings(string word1, string word2) { vector<int> mp1(26,0); vector<int> mp2(26,0); if(word1.size() != word2.size()) return 0 ; for (int i = 0 ; i < word1.size() ; i++){ mp1[word1[i] - 'a']++; mp2[word2[i] - 'a']++; } for (int i = 0; i < 26; i++) { if ((mp1[i] == 0) != (mp2[i] == 0)) return false; } int n1 = *max_element(mp1.begin(), mp1.end()); int n2 = *max_element(mp2.begin(), mp2.end()); if (n1 != n2) return false; vector<int> mp11(n1+1,0); vector<int> mp22(n2+1,0); for ( int i =0 ; i < 26 ; i++){ mp11[mp1[i]]++; mp22[mp2[i]]++; } if(mp11 != mp22) return false ; return true ; } }; ```
3
0
['C++']
0
determine-if-two-strings-are-close
Java Solution
java-solution-by-sardartirtho003-1cog
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach : \nThe first operation allows character swaps, and the second allows rema
sardartirtho003
NORMAL
2024-11-28T15:26:34.739879+00:00
2024-11-28T15:26:34.739913+00:00
309
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach : \nThe first operation allows character swaps, and the second allows remapping character frequencies. Matching unique characters and sorted frequencies ensures the transformation is possible.\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```java []\nclass Solution {\n public boolean closeStrings(String word1, String word2) {\n if (word1.length() != word2.length()) {\n return false;\n }\n \n int[] freq1 = new int[26];\n int[] freq2 = new int[26];\n Set<Character> set1 = new HashSet<>();\n Set<Character> set2 = new HashSet<>();\n \n for (char c : word1.toCharArray()) {\n freq1[c - \'a\']++;\n set1.add(c);\n }\n \n for (char c : word2.toCharArray()) {\n freq2[c - \'a\']++;\n set2.add(c);\n }\n \n if (!set1.equals(set2)) {\n return false;\n }\n \n Arrays.sort(freq1);\n Arrays.sort(freq2);\n \n for (int i = 0; i < 26; i++) {\n if (freq1[i] != freq2[i]) {\n return false;\n }\n }\n \n return true; \n }\n}\n```
3
0
['Java']
0
determine-if-two-strings-are-close
Solution By Dare2Solve | Detailed Explanation | Clean Code
solution-by-dare2solve-detailed-explanat-3ovp
Explanation []\nauthorslog.com/blog/BbN5R6bm5D\n\n# Code\n\ncpp []\nclass Solution {\npublic:\n bool checkIsUnique(unordered_set<char>& set1, unordered_set<c
Dare2Solve
NORMAL
2024-08-19T07:47:38.095267+00:00
2024-08-19T07:47:38.095284+00:00
347
false
```Explanation []\nauthorslog.com/blog/BbN5R6bm5D\n```\n# Code\n\n```cpp []\nclass Solution {\npublic:\n bool checkIsUnique(unordered_set<char>& set1, unordered_set<char>& set2) {\n for (char c : set1) {\n if (set2.find(c) == set2.end()) return false;\n }\n return true;\n }\n\n bool FrequencyOfChars(unordered_map<char, int>& word1, unordered_map<char, int>& word2) {\n vector<int> one, two;\n\n for (auto& [key, value] : word1) {\n one.push_back(value);\n }\n for (auto& [key, value] : word2) {\n two.push_back(value);\n }\n\n sort(one.begin(), one.end());\n sort(two.begin(), two.end());\n\n if (one.size() != two.size()) return false;\n\n for (size_t i = 0; i < one.size(); i++) {\n if (one[i] != two[i]) return false;\n }\n return true;\n }\n\n bool closeStrings(string word1, string word2) {\n if (word1.length() != word2.length()) return false;\n\n unordered_map<char, int> Map1, Map2;\n\n for (size_t i = 0; i < word1.length(); i++) {\n Map1[word1[i]]++;\n Map2[word2[i]]++;\n }\n\n unordered_set<char> uniqueWord1(word1.begin(), word1.end());\n unordered_set<char> uniqueWord2(word2.begin(), word2.end());\n\n if (!checkIsUnique(uniqueWord1, uniqueWord2)) return false;\n\n return FrequencyOfChars(Map1, Map2);\n }\n};\n```\n\n```python []\nclass Solution:\n def checkIsUnique(self, set1, set2):\n for c in set1:\n if c not in set2:\n return False\n return True\n\n def FrequencyOfChars(self, word1, word2):\n one = sorted(word1.values())\n two = sorted(word2.values())\n \n if len(one) != len(two):\n return False\n\n for i in range(len(one)):\n if one[i] != two[i]:\n return False\n return True\n\n def closeStrings(self, word1: str, word2: str) -> bool:\n if len(word1) != len(word2):\n return False\n\n Map1 = {}\n Map2 = {}\n\n for i in range(len(word1)):\n Map1[word1[i]] = Map1.get(word1[i], 0) + 1\n Map2[word2[i]] = Map2.get(word2[i], 0) + 1\n\n uniqueWord1 = set(word1)\n uniqueWord2 = set(word2)\n\n if not self.checkIsUnique(uniqueWord1, uniqueWord2):\n return False\n\n return self.FrequencyOfChars(Map1, Map2)\n```\n\n```java []\n\npublic class Solution {\n private boolean checkIsUnique(Set<Character> set1, Set<Character> set2) {\n for (char c : set1) {\n if (!set2.contains(c)) return false;\n }\n return true;\n }\n\n private boolean FrequencyOfChars(Map<Character, Integer> word1, Map<Character, Integer> word2) {\n List<Integer> one = new ArrayList<>(word1.values());\n List<Integer> two = new ArrayList<>(word2.values());\n\n Collections.sort(one);\n Collections.sort(two);\n\n for (int i = 0; i < one.size(); i++) {\n if (!one.get(i).equals(two.get(i))) return false;\n }\n return true;\n }\n\n public boolean closeStrings(String word1, String word2) {\n if (word1.length() != word2.length()) return false;\n\n Map<Character, Integer> Map1 = new HashMap<>();\n Map<Character, Integer> Map2 = new HashMap<>();\n\n for (int i = 0; i < word1.length(); i++) {\n Map1.put(word1.charAt(i), Map1.getOrDefault(word1.charAt(i), 0) + 1);\n Map2.put(word2.charAt(i), Map2.getOrDefault(word2.charAt(i), 0) + 1);\n }\n\n Set<Character> uniqueWord1 = new HashSet<>(word1.chars().mapToObj(c -> (char) c).toList());\n Set<Character> uniqueWord2 = new HashSet<>(word2.chars().mapToObj(c -> (char) c).toList());\n\n if (!checkIsUnique(uniqueWord1, uniqueWord2)) return false;\n\n return FrequencyOfChars(Map1, Map2);\n }\n}\n```\n\n```javascript []\nvar closeStrings = (word1,word2) => {\n if(word1.length != word2.length) return false\n\n const Map1 = {}\n const Map2 = {}\n for(let i = 0 ; i<word1.length ; i++){\n if(Map1[word1[i]]){\n Map1[word1[i]]++\n }else{\n Map1[word1[i]] = 1\n }\n\n if(Map2[word2[i]]){\n Map2[word2[i]]++\n }else{\n Map2[word2[i]] = 1\n }\n \n }\n\n const uniqueWord1 = new Set(word1)\n const uniqueWord2 = new Set(word2)\n\n if(!checkIsUnique(uniqueWord1,uniqueWord2)) return false\n // console.log(checkIsUnique(uniqueWord1,uniqueWord2))\n return FrequencyOfChars(Map1,Map2) \n}\nfunction checkIsUnique(set1,set2){\n for(let i of set1){\n if(!set2.has(i)) return false\n }\n return true\n}\nfunction FrequencyOfChars (word1,word2) {\n let one = Object.values(word1).sort((a,b) => a-b)\n let two = Object.values(word2).sort((a,b) => a-b)\n console.log(one,two)\n for(let i = 0 ; i < one.length ; i++){\n if(one[i] != two[i]) return false\n }\n return true\n}\n```
3
0
['Hash Table', 'Sorting', 'Counting', 'Python', 'C++', 'Java', 'Python3', 'JavaScript']
0
determine-if-two-strings-are-close
Easiest python solution beating 98.33% people with explanation🤗
easiest-python-solution-beating-9833-peo-jref
\n\n\n1. Check if both the words are made up of same letters i.e. either of the words shouldn\'t have a letter that is not common. If not retrun False. if yes f
Parneetkaur2917
NORMAL
2024-07-22T17:32:02.157887+00:00
2024-07-22T17:32:02.157910+00:00
302
false
![image.png](https://assets.leetcode.com/users/images/189ff802-8639-4d91-a9f7-9a7a790ef68f_1721669496.3377306.png)\n\n\n1. Check if both the words are made up of same letters i.e. either of the words shouldn\'t have a letter that is not common. If not retrun False. if yes follow step 2.\n2. Now, count the number of times these letters appear in both of the words and make a list for each. After sorting if these lists are eqaul then return true else False. This is because the second rule allows us to change all the occurences of a letter.\n\n# Code\n```\nclass Solution(object):\n def closeStrings(self, word1, word2):\n """\n :type word1: str\n :type word2: str\n :rtype: bool\n """\n uw1=list(set(word1))\n uw2=list(set(word2))\n if sorted(uw1)!=sorted(uw2):\n return False\n else:\n c1=[]\n c2=[]\n for i in uw1:\n x=word1.count(i)\n c1.append(x)\n for i in uw2:\n x=word2.count(i)\n c2.append(x)\n if sorted(c1)==sorted(c2):\n return True\n else:\n return False\n \n```
3
0
['Python']
1
determine-if-two-strings-are-close
Python One-liner
python-one-liner-by-braveblc-ut72
Intuition\nBecause we can swap the position of any character, we only care about the frequency of what\'s in each string, as long as they have the same letters.
BraveBLC
NORMAL
2024-02-19T04:24:17.914125+00:00
2024-02-19T04:24:17.914157+00:00
147
false
# Intuition\nBecause we can swap the position of any character, we only care about the frequency of what\'s in each string, as long as they have the same letters. This indicates using a hashmap. \n\n\nBecause every occurence of one letter can be swapped, we only need to check if both strings have the same frequencies. In other words, they both must have the same frequencies of frequencies.\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nI made a counter which is a hashmap/dictionary of each character and the frequency of each. I then made a counter of the values (the frequencies), which will make the keys the frequencies of the characters, and the values will be the frequencies of those frequencies. \n\nAt the end, we must check if those dictionaries are equal, but then also make sure that the keys of the dictionaries of the frequencies of the characters are equal, which will ensure that both strings contain the same characters of the alphabet.\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def closeStrings(self, word1: str, word2: str) -> bool:\n return Counter(Counter(word1).values()) == Counter(Counter(word2).values()) and Counter(word1).keys()==Counter(word2).keys()\n \n```
3
0
['Python', 'Python3']
0
determine-if-two-strings-are-close
Python easy solution !
python-easy-solution-by-abdelhalim1-p3hs
Intuition\n Describe your first thoughts on how to solve this problem. \nThe problem requires determining if two strings are "close" based on specific criteria
abdelhalim1
NORMAL
2024-01-14T20:22:43.965881+00:00
2024-01-14T20:22:43.965906+00:00
94
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem requires determining if two strings are "close" based on specific criteria related to length, character sets, and frequency distributions. My initial thoughts are to create frequency dictionaries for each word and compare these dictionaries along with other properties such as set of characters and length.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nThe solution involves creating frequency dictionaries for characters in both word1 and word2. After constructing these dictionaries, we sort the frequency values and compare them. Additionally, we create sets for both words\' characters and compare these sets. The final check ensures that the lengths of the two words are equal. The approach leverages Python\'s built-in functions for dictionary manipulation and set operations\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n**O(l1 * log * l1 + l2 * log * l2)**\nSorting frequency lists dominates the time complexity.\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n **O( l1 + l2)**\nStorage for frequency dictionaries. The space complexity is also influenced by the creation of sets for the characters in each word.\n# Code\n```\nclass Solution:\n def closeStrings(self, word1: str, word2: str) -> bool:\n l1 = len(word1)\n l2 = len(word2)\n freq1 = {}\n freq2 = {}\n\n for ch in word1:\n freq1[ch] = freq1.get(ch, 0) + 1\n\n for ch in word2:\n freq2[ch] = freq2.get(ch, 0) + 1\n\n arr1 = sorted(list(freq1.values()))\n arr2 = sorted(list(freq2.values()))\n s1 = set(word1)\n s2 = set(word2)\n\n return len(word1) == len(word2) and s1 == s2 and arr1 == arr2\n```
3
0
['Python3']
0
determine-if-two-strings-are-close
✅ 🚀 51ms, 100% Speed, O(N log N). JS
51ms-100-speed-on-log-n-js-by-artme-om1u
Intuition\nTo determine if two strings word1 and word2 are close, the key is to understand that both operations (swapping any two characters or transforming occ
ArtMe
NORMAL
2024-01-14T19:09:42.796163+00:00
2024-01-14T19:09:42.796189+00:00
123
false
# Intuition\nTo determine if two strings `word1` and `word2` are close, the key is to understand that both operations (swapping any two characters or transforming occurrences of one character into another) do not affect the frequency of characters in the strings. Thus, two strings are close if they have the same characters with the same frequencies, regardless of their order.\n\n# Approach\n1. **Length Check**: First, if `word1` and `word2` are of different lengths, they cannot be close. This is because operations do not change the length of the string.\n\n2. **Identity Check**: If `word1` and `word2` are identical, they are trivially close.\n\n3. **Frequency Counting**: For each string, count the frequency of each character. This is done by initializing two arrays of length 26 (for each letter of the alphabet), and incrementing the count for the corresponding character.\n\n4. **Character Existence Check**: Ensure that both strings contain the same set of characters. If one string contains a character not present in the other, they cannot be close.\n\n5. **Frequency Matching**: The solution involves sorting the character frequency arrays of both `word1` and `word2`. The strings are considered close if these sorted frequency arrays are identical, indicating that both strings have the same set of character frequencies, irrespective of the specific characters. This alignment in frequencies is crucial, as the allowed operations do not alter the number of occurrences of each character.\n\n# Complexity\n- **Time complexity**: The time complexity is $$O(n \\log n)$$, where $$n$$ is the length of the strings. This is because the most time-consuming operation is sorting the frequency arrays.\n\n- **Space complexity**: The space complexity is $$O(1)$$, since the extra space used (two arrays of fixed size 26) does not depend on the input size.\n\n# Code\n```\n/**\n * @param {string} word1\n * @param {string} word2\n * @return {boolean}\n */\nvar closeStrings = function(word1, word2) {\n if (word1.length !== word2.length) {\n return false;\n }\n if (word1 == word2) {\n return true;\n }\n let arr1 = Array(26).fill(0);\n let arr2 = Array(26).fill(0);\n const aCode = \'a\'.charCodeAt(0);\n for (i = 0; i < word1.length; i++) {\n arr1[word1.charCodeAt(i) - aCode]++;\n arr2[word2.charCodeAt(i) - aCode]++;\n }\n for (let i = 0; i < arr1.length;i++){\n if (!arr1[i] && arr2[i] > 0 || arr1[i] > 0 && !arr2[i]) {\n return false;\n }\n }\n arr1.sort();\n arr2.sort();\n for (let i = 0; i < arr1.length; i++) {\n if (arr1[i] !== arr2[i]) {\n return false;\n }\n }\n return true;\n};\n```\n\n![Screenshot 2024-01-14 at 21.56.16.png](https://assets.leetcode.com/users/images/3de1b170-44e2-40b7-b1d8-5e0a8528c188_1705258909.6454906.png)\n
3
0
['JavaScript']
0
minimum-number-of-operations-to-convert-time
C++ Greedy
c-greedy-by-lzl124631x-qocc
\nSee my latest update in repo LeetCode\n\n## Solution 1. Greedy\n\n Compute the time difference in seconds\n Greedily using 60, 15, 5, 1 operations. For each o
lzl124631x
NORMAL
2022-04-03T04:02:00.760476+00:00
2022-04-03T04:02:00.760530+00:00
5,114
false
\nSee my latest update in repo [LeetCode](https://github.com/lzl124631x/LeetCode)\n\n## Solution 1. Greedy\n\n* Compute the time difference in seconds\n* Greedily using `60, 15, 5, 1` operations. For each operation `op`, we use `diff / op` number of operations to turn `diff` to `diff % op`.\n\n```cpp\n// OJ: https://leetcode.com/contest/weekly-contest-287/problems/minimum-number-of-operations-to-convert-time/\n// Author: github.com/lzl124631x\n// Time: O(1)\n// Space: O(1)\nclass Solution {\n int getTime(string &s) {\n return stoi(s.substr(0, 2)) * 60 + stoi(s.substr(3));\n }\npublic:\n int convertTime(string current, string correct) {\n int diff = getTime(correct) - getTime(current), ops[4] = {60,15,5,1}, ans = 0;\n for (int op : ops) {\n ans += diff / op;\n diff %= op;\n }\n return ans;\n }\n};\n```
83
0
[]
11
minimum-number-of-operations-to-convert-time
Convert to minutes
convert-to-minutes-by-votrubac-wgjo
Since we can only add minutes, the greedy approach would work.\n\nC++\ncpp \nint convertTime(string current, string correct) {\n auto toMin = [](string &s
votrubac
NORMAL
2022-04-03T04:01:57.877501+00:00
2022-04-03T07:03:23.919915+00:00
4,270
false
Since we can only add minutes, the greedy approach would work.\n\n**C++**\n```cpp \nint convertTime(string current, string correct) {\n auto toMin = [](string &s) { \n \xA0 \xA0 \xA0 \xA0return s[0] * 600 + s[1] * 60 + s[3] * 10 + s[4] ;\n };\n int d = toMin(correct) - toMin(current);\n return d / 60 + d % 60 / 15 + d % 15 / 5 + d % 5;\n}\n```
61
0
['C']
21
minimum-number-of-operations-to-convert-time
⭐Easy Python Solution | Convert time to minutes
easy-python-solution-convert-time-to-min-oebs
Convert times into minutes and then the problem becomes simpler. \n2. To minimize the number of total operations we try to use the largest possible change from
ancoderr
NORMAL
2022-04-03T04:02:07.498074+00:00
2022-05-16T14:58:45.397605+00:00
3,051
false
1. Convert times into minutes and then the problem becomes simpler. \n2. To minimize the number of total operations we try to use the largest possible change from `[60,15,5,1]` till possible.\n```\nclass Solution:\n def convertTime(self, current: str, correct: str) -> int:\n current_time = 60 * int(current[0:2]) + int(current[3:5]) # Current time in minutes\n target_time = 60 * int(correct[0:2]) + int(correct[3:5]) # Target time in minutes\n diff = target_time - current_time # Difference b/w current and target times in minutes\n count = 0 # Required number of operations\n\t\t# Use GREEDY APPROACH to calculate number of operations\n for i in [60, 15, 5, 1]:\n count += diff // i # add number of operations needed with i to count\n diff %= i # Diff becomes modulo of diff with i\n return count\n```\n
37
0
['Python', 'Python3']
4
minimum-number-of-operations-to-convert-time
Java | Loop | Easy To Understand
java-loop-easy-to-understand-by-sudhansh-f7ht
Here I am discussing my approach to this problem\nApproach:\n1. Convert both current time and correct time into minutes.\n2. Increase current time by 60min unti
SudhanshuMallick
NORMAL
2022-04-03T04:08:16.677164+00:00
2022-04-03T04:08:16.677190+00:00
2,238
false
**Here I am discussing my approach to this problem**\n**Approach:**\n1. Convert both **current time** and **correct time** into **minutes**.\n2. **Increase** **current time** by 60min until it becomes **just less or equal to correct time**.\n3. Similarly do the **same thing** with 15min, 5min, and 1min window.\n4. Count the **number of iterations** performed.\n5. Return the number of iterations.\n\n**Source Code:**\n```\nclass Solution {\n public int convertTime(String current, String correct) {\n String[] curr = current.split(":");\n String[] corr = correct.split(":");\n int cur = Integer.parseInt(curr[0]) * 60 + Integer.parseInt(curr[1]);\n int cor = Integer.parseInt(corr[0]) * 60 + Integer.parseInt(corr[1]);\n int count = 0;\n \n while(cur + 60 <= cor) {\n ++count;\n cur += 60;\n }\n \n while(cur + 15 <= cor) {\n ++count;\n cur += 15;\n }\n \n while(cur + 5 <= cor) {\n ++count;\n cur += 5;\n }\n \n while(cur + 1 <= cor) {\n ++count;\n cur += 1;\n }\n \n return count;\n \n }\n}\n```\n\n**Complexity Analysis:**\n```\nTime Complexity: O(c) // c some constant value <= 100\nSpace Complexity : O(1)\n```
23
0
['Java']
7
minimum-number-of-operations-to-convert-time
Short Java, 5 lines
short-java-5-lines-by-climberig-dzcp
```java\n public int convertTime(String current, String correct){\n Function parse = t -> Integer.parseInt(t.substring(0, 2)) * 60 + Integer.parseInt(t.s
climberig
NORMAL
2022-04-03T04:17:07.144773+00:00
2022-04-06T03:40:05.142927+00:00
2,312
false
```java\n public int convertTime(String current, String correct){\n Function<String, Integer> parse = t -> Integer.parseInt(t.substring(0, 2)) * 60 + Integer.parseInt(t.substring(3));\n int diff = parse.apply(correct) - parse.apply(current), ops[] = {60, 15, 5, 1}, r = 0;\n for(int i = 0; i < ops.length && diff > 0; diff = diff % ops[i++])\n r += diff / ops[i];\n return r;\n }
21
0
['Java']
4
minimum-number-of-operations-to-convert-time
C++ Solution 0ms 100% Faster 💫💫💫
c-solution-0ms-100-faster-by-himanshu_52-bech
"""\nclass Solution {\npublic:\n int convertTime(string current, string correct) {\n int hour1=(current[0]-\'0\')10+(current[1]-\'0\');\n int h
himanshu_52
NORMAL
2022-04-03T05:15:23.802203+00:00
2022-04-03T05:28:51.120775+00:00
1,008
false
"""\nclass Solution {\npublic:\n int convertTime(string current, string correct) {\n int hour1=(current[0]-\'0\')*10+(current[1]-\'0\');\n int hour2=(correct[0]-\'0\')*10+(correct[1]-\'0\');\n int minute1=(current[3]-\'0\')*10+(current[4]-\'0\');\n int minute2=(correct[3]-\'0\')*10+(correct[4]-\'0\');\n \n int total=(hour2-hour1)*60+ (minute2-minute1);\n int res=0;\n if(total>=60){\n int temp=(total/60);\n total-=(temp*60);\n res+=temp;\n }\n if(total>=15){\n int temp=(total/15);\n total-=(temp*15);\n res+=temp;\n }\n if(total>=5){\n int temp=(total/5);\n total-=(temp*5);\n res+=temp;\n }\n res+=total;\n return res;\n }\n};\n"""\n\tPlease Upvote if you Find it Helpful \uD83D\uDE42.
13
0
['Math', 'C']
1
minimum-number-of-operations-to-convert-time
C++ Greedy Convert to minutes
c-greedy-convert-to-minutes-by-devendray-eyyn
\nclass Solution {\npublic:\n int convertTime(string current, string co) {\n \n string h1="";\n string m1="";\n string h2="";\n
devendrayadav_102
NORMAL
2022-04-03T04:31:46.170546+00:00
2022-04-03T04:31:46.170587+00:00
939
false
```\nclass Solution {\npublic:\n int convertTime(string current, string co) {\n \n string h1="";\n string m1="";\n string h2="";\n string m2="";\n \n h1+=current[0];\n h1+=current[1];\n \n m1+=current[3];\n m1+=current[4];\n \n h2+=co[0];\n h2+=co[1];\n \n m2+=co[3];\n m2+=co[4];\n \n \n int min1=stoi(h1)*60+stoi(m1);\n int min2=stoi(h2)*60+stoi(m2);\n \n // int x=min2-min1;\n int count=0;\n \n while(min2>min1){\n \n if((min2-min1)>=60){\n min1=min1+60;\n count++;\n }\n else if((min2-min1)>=15){\n min1=min1+15;\n count++;\n }\n else if((min2-min1)>=5){\n min1=min1+5;\n count++;\n }\n else {\n count+=(min2-min1);\n min1=min1+(min2-min1);\n }\n }\n return count;\n \n }\n};\n```
8
0
['C']
1
minimum-number-of-operations-to-convert-time
✅ cpp easy || Greedy || Explained || faster than 100%
cpp-easy-greedy-explained-faster-than-10-fv3g
```\n1. extract the hours and minutes from both the strings\n2. convert the strings to numbers\n3. convert both time time to minutes.\n4. calculate the minutes
namanvijay814
NORMAL
2022-04-03T04:05:28.977272+00:00
2022-04-03T04:14:50.593003+00:00
907
false
```\n1. extract the hours and minutes from both the strings\n2. convert the strings to numbers\n3. convert both time time to minutes.\n4. calculate the minutes difference.\n5. simply check minimum operations to make minutes equal to difference.\nclass Solution {\npublic:\n int convertTime(string a, string b) {\n int x=a[0]-\'0\',y=a[1]-\'0\',z=a[3]-\'0\',w=a[4]-\'0\';\n int p=b[0]-\'0\',q=b[1]-\'0\',r=b[3]-\'0\',s=b[4]-\'0\';\n int hr1 = (x)*10+(y);\n int m1 = (z)*10+(w);\n int hr2 = (p)*10+(q);\n int m2 = (r)*10+s;\n int num1 = hr1*60+m1;\n int num2 = hr2*60+m2;\n int diff = num2-num1;\n int res=0;\n int arr[4]={60,15,5,1};\n for(int i=0;i<4;i++){\n res+=diff/arr[i];\n diff = diff%arr[i];\n }\n return res;\n }\n};
8
0
['C++']
4
minimum-number-of-operations-to-convert-time
🔥[Python 3] Convert to minutes and find parts using divmod, beats 85%
python-3-convert-to-minutes-and-find-par-efko
\nclass Solution:\n def convertTime(self, current: str, correct: str) -> int:\n def toMinutes(s):\n h, m = s.split(\':\')\n retu
yourick
NORMAL
2023-06-19T14:22:12.338008+00:00
2023-06-19T14:22:12.338028+00:00
427
false
```\nclass Solution:\n def convertTime(self, current: str, correct: str) -> int:\n def toMinutes(s):\n h, m = s.split(\':\')\n return 60 * int(h) + int(m)\n \n minutes = toMinutes(correct) - toMinutes(current)\n hours, minutes = divmod(minutes, 60)\n quaters, minutes = divmod(minutes, 15)\n fives, minutes = divmod(minutes, 5)\n\n return hours + quaters + fives + minutes\n```
7
0
['Python', 'Python3']
0
minimum-number-of-operations-to-convert-time
[JavaScript] Clean O(N) Solution
javascript-clean-on-solution-by-yogipatu-mmge
\nvar convertTime = function(current, correct) {\n // 1. Seperate current and correct into Hours and Minutes\n const currentHoursMins = current.split(":")
YogiPaturu
NORMAL
2022-04-03T04:25:35.390190+00:00
2022-04-03T04:25:35.390235+00:00
291
false
```\nvar convertTime = function(current, correct) {\n // 1. Seperate current and correct into Hours and Minutes\n const currentHoursMins = current.split(":");\n const correctHoursMins = correct.split(":");\n \n // 2. Calculate difference in minutes\n let minDifference = ((correctHoursMins[1] - currentHoursMins[1])) + ((correctHoursMins[0] - currentHoursMins[0]) * 60);\n\n // 3. Greedily take the highest minutes to lowest minutes\n let operations = 0;\n const operationValues = [60, 15, 5, 1] // this format is maintainable and extensible since other values can easily be added\n for(const difference of operationValues){\n while(minDifference >= difference){\n minDifference -= difference;\n operations++;\n }\n }\n \n return operations;\n};\n```
6
0
['Greedy', 'JavaScript']
3
minimum-number-of-operations-to-convert-time
simple and easy Python solution 😍❤️‍🔥
simple-and-easy-python-solution-by-shish-drwy
\n# if it\'s help, please up \u2B06 vote! \u2764\uFE0F\n\n###### Let\'s Connect on LinkedIn: www.linkedin.com/in/shishirrsiam\n###### Let\'s Connect on Facebook
shishirRsiam
NORMAL
2024-08-16T01:40:39.969234+00:00
2024-08-16T01:40:39.969261+00:00
212
false
\n# if it\'s help, please up \u2B06 vote! \u2764\uFE0F\n\n###### Let\'s Connect on LinkedIn: www.linkedin.com/in/shishirrsiam\n###### Let\'s Connect on Facebook: www.fb.com/shishirrsiam\n\n\n\n# Complexity\n- Time complexity: O(1)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution(object):\n def convertTime(self, current, correct):\n cur = int(current[:2]) * 60 + int(current[3:])\n target = int(correct[:2]) * 60 + int(correct[3:])\n dif = target - cur\n\n ans = 0\n times = [60, 15, 5, 1]\n for time in times:\n if(dif == 0): break\n ans += dif // time\n dif %= time\n return ans\n```
5
0
['String', 'Greedy', 'Python', 'Python3']
3
minimum-number-of-operations-to-convert-time
Solution in 6 languages | O(1) Time and O(1) Space Complexity |0ms | implementation |
solution-in-6-languages-o1-time-and-o1-s-yv0t
Pls upvote(\uD83E\uDD7A\uD83D\uDE48\uD83D\uDE0C). If you found it useful\n\nJust convert time of the day to minutes and iterate over 60,15,5,1 minutes to get th
harishdatla
NORMAL
2022-04-09T13:53:28.222449+00:00
2022-04-10T13:04:46.573701+00:00
530
false
**Pls upvote(\uD83E\uDD7A\uD83D\uDE48\uD83D\uDE0C). If you found it useful**\n\nJust convert time of the day to minutes and iterate over 60,15,5,1 minutes to get the number of ops.\n\nPlease suggest any improvements language wise or algorithmwise, im only well verse in c++,golang. I use the rest of languages on need by basis at work.\n\nPlease comment if u have any doubts, will be happy to reply\n\nC++\n```\nclass Solution {\npublic:\n int HHMMToMinutes(string s){\n return stoi(s.substr(0,2))*60 + stoi(s.substr(3,2));\n }\n int convertTime(string current, string correct) {\n int diff = - HHMMToMinutes(current) + HHMMToMinutes(correct);\n vector<int> order = {60,15,5,1};\n int i = 0;\n int ans = 0;\n while(i < 4){\n ans+=(diff/order[i]);\n diff%=order[i];\n i++;\n }\n \n return ans;\n }\n};\n```\nJava\n\n```\nclass Solution {\n public int HHMMToMinutes(String s){\n return Integer.parseInt(s.substring(0,2))*60 + Integer.parseInt(s.substring(3,5)) ;\n }\n public int convertTime(String current, String correct) {\n int diff = HHMMToMinutes(correct) - HHMMToMinutes(current);\n int[] order = {60,15,5,1};\n int i = 0;\n int ops = 0;\n while(i < 4){\n ops+=(diff/order[i]);\n diff%=order[i];\n i++;\n }\n return ops;\n }\n}\n```\nPython\n```\nclass Solution:\n def HHMMToMinutes(self, s: str) -> int:\n return int(s[0:2])*60 + int(s[3:5])\n def convertTime(self, current: str, correct: str) -> int:\n diff = self.HHMMToMinutes(correct) - self.HHMMToMinutes(current)\n order = [60,15,5,1]\n ops = 0\n for i in range(0,4):\n ops+=int(diff/order[i])\n diff%=order[i]\n return ops\n```\nJavascript\n\n```\nvar getTime = function(time){\n var [hrs,mins] = time.split(":");\n return parseInt(hrs)*60 + parseInt(mins);\n}\n\n\nvar convertTime = function(current, correct) {\n var diff = getTime(correct) - getTime(current);\n var order = [60,15,5,1];\n var ops = 0;\n order.forEach(val =>{\n ops+=Math.floor((diff/val));\n diff%=val;\n })\n return ops;\n};\n```\n\nGolang\n```\nimport "strconv"\nfunc HHMMToMinutes(s string) int{\n sr := strings.Split(s,":")\n hrs,_ := strconv.Atoi(sr[0])\n minutes,_ := strconv.Atoi(sr[1]) \n return hrs*60 + minutes \n}\nfunc convertTime(current string, correct string) int {\n diff := HHMMToMinutes(correct) - HHMMToMinutes(current)\n order := [4]int{60,15,5,1}\n ops := 0\n for i := 0 ; i < 4 ; i++ {\n ops+=(diff/order[i])\n diff%=order[i]\n }\n return ops\n}\n```\n\nKotlin\n```\nclass Solution {\n fun HHMMToMinutes(s: String): Int{\n return Integer.parseInt(s.subSequence(0,2).toString())*60+Integer.parseInt(s.subSequence(3,5).toString())\n }\n fun convertTime(current: String, correct: String): Int {\n var diff = HHMMToMinutes(correct) - HHMMToMinutes(current)\n var ops = 0\n val order = intArrayOf(60,15,5,1)\n println(diff)\n for(i in 0..3){\n ops+=(diff/order[i])\n diff%=order[i]\n }\n return ops\n }\n}\n```\n\n
5
0
['C', 'Python', 'C++', 'Java', 'Go', 'Kotlin']
0
minimum-number-of-operations-to-convert-time
JavaScript Solution
javascript-solution-by-sronin-v5bu
Found this solution helpful? Consider showing support by upvoting this post.\nHave a question? Kindly leave a comment below.\nThank you and happy hacking!\n\nco
sronin
NORMAL
2022-04-08T01:38:24.157553+00:00
2022-04-09T01:36:54.161515+00:00
510
false
Found this solution helpful? Consider showing support by upvoting this post.\nHave a question? Kindly leave a comment below.\nThank you and happy hacking!\n```\nconst convertTime = (current, correct) => {\n if (current === correct) return 0\n\t\n let count = 0\n let currentInMins = parseInt(current.slice(3)) + parseInt(current.slice(0, 2)) * 60\n let correcttInMins = parseInt(correct.slice(3)) + parseInt(correct.slice(0, 2)) * 60\n let minuteDifference = correcttInMins - currentInMins\n\n while (minuteDifference !== 0) {\n if (minuteDifference % 60 === 0) {\n minuteDifference -= 60\n count++\n }\n else if (minuteDifference % 15 === 0) {\n minuteDifference -= 15\n count++\n }\n else if (minuteDifference % 5 === 0) {\n minuteDifference -= 5\n count++\n }\n else{\n minuteDifference -= 1\n count++\n }\n }\n\n return count\n};\n```
5
0
['JavaScript']
2
minimum-number-of-operations-to-convert-time
Intutive || EasyToUnderstand || Greedy
intutive-easytounderstand-greedy-by-craz-x2s2
```\nclass Solution {\npublic:\n int convertTime(string current, string correct) {\n int curr_hour = stoi(current.substr(0,2));\n int curr_min
crazy_zoker
NORMAL
2022-04-03T04:01:43.914077+00:00
2022-04-03T04:10:51.189044+00:00
399
false
```\nclass Solution {\npublic:\n int convertTime(string current, string correct) {\n int curr_hour = stoi(current.substr(0,2));\n int curr_min = stoi(current.substr(3,2));\n int co_hour = stoi(correct.substr(0,2));\n int co_min = stoi(correct.substr(3,2));\n \n \n int h_diff = co_hour - curr_hour;\n int min_diff = co_min - curr_min;\n \n int total = h_diff*60 + min_diff; //Calculate The Total Minutes\n vector<int>time{1,5,15,60};\n \n int op = 0; // Perform the Greedy Operation\n for(int i = time.size() -1;i>=0;i--){\n if(total >= time[i] && total >0){\n op+=total/time[i]; \n total = total%time[i];\n }\n }\n \n \n \n return op;\n }\n};
5
0
[]
1
minimum-number-of-operations-to-convert-time
Python Easy
python-easy-by-true-detective-fkdf
first compute the hour and minute difference\n\nif minute difference is negative then we must change the diffs\n\nthen greedily subtract the remainder to 15, 5,
true-detective
NORMAL
2022-04-06T05:41:30.908199+00:00
2022-04-06T05:41:30.908245+00:00
358
false
first compute the hour and minute difference\n\nif minute difference is negative then we must change the diffs\n\nthen greedily subtract the remainder to 15, 5, 1 from minutes.\n```\nclass Solution:\n def convertTime(self, current: str, correct: str) -> int:\n h1, m1 = current.split(\':\')\n h2, m2 = correct.split(\':\')\n h = int(h2) - int(h1)\n m = int(m2) - int(m1)\n if m < 0:\n h -= 1\n m += 60\n \n a = m // 15\n m %= 15\n b = m // 5\n m %= 5\n return h + a + b + m\n```
4
0
[]
1
minimum-number-of-operations-to-convert-time
Rust solution
rust-solution-by-bigmih-j36w
\nimpl Solution {\n pub fn convert_time(current: String, correct: String) -> i32 {\n if current == correct {\n return 0;\n }\n\n
BigMih
NORMAL
2022-04-03T09:36:41.362297+00:00
2022-04-03T09:36:41.362344+00:00
90
false
```\nimpl Solution {\n pub fn convert_time(current: String, correct: String) -> i32 {\n if current == correct {\n return 0;\n }\n\n let to_num = |s: &str| -> i32 { s.parse().unwrap() };\n let (h2, m2) = (to_num(&correct[..2]), to_num(&correct[3..]));\n let (h1, m1) = (to_num(&current[..2]), to_num(&current[3..]));\n\n let mut delta = (m2 - m1) + 60 * if h2 >= h1 { h2 - h1 } else { h2 - h1 + 24 };\n let mut res = 0;\n\n for op in [60, 15, 5] {\n res += delta / op;\n delta %= op;\n }\n\n res + delta\n }\n}\n```
4
0
[]
0
minimum-number-of-operations-to-convert-time
Java Time Conversion New
java-time-conversion-new-by-aditya_jain_-a4ji
\nclass Solution {\n public static int convertTime(String current, String correct) {\n\t\tint start = Integer.parseInt(current.substring(0, 2)) * 60 + Intege
Aditya_jain_2584550188
NORMAL
2022-04-03T06:15:16.541092+00:00
2022-04-03T06:15:16.541127+00:00
328
false
```\nclass Solution {\n public static int convertTime(String current, String correct) {\n\t\tint start = Integer.parseInt(current.substring(0, 2)) * 60 + Integer.parseInt(current.substring(3));\n\t\tint goal = Integer.parseInt(correct.substring(0, 2)) * 60 + Integer.parseInt(correct.substring(3));\n\n//\t\tSystem.out.println(start);\n//\t\tSystem.out.println(goal);\n\t\tint count = 0;\n\t\twhile (goal != start) {\n\t\t\tint diff = goal - start;\n\t\t\tif (diff >= 60) {\n\t\t\t\tgoal = goal - 60;\n\t\t\t\tcount++;\n\t\t\t} else if (diff >= 15) {\n\t\t\t\tgoal = goal - 15;\n\t\t\t\tcount++;\n\t\t\t} else if (diff >=5) {\n\t\t\t\tgoal = goal - 5;\n\t\t\t\tcount++;\n\t\t\t} else if (diff >= 1) {\n\t\t\t\tgoal = goal - 1;\n\t\t\t\tcount++;\n\t\t\t}\n\t\t}\n\t\treturn count;\n\t}\n}\n```
4
0
['String', 'Java']
0
minimum-number-of-operations-to-convert-time
Python convert to minutes
python-convert-to-minutes-by-gauau-8g3l
\ndef convertTime(self, current: str, correct: str) -> int:\n\tans = 0\n\th, m = list(map(int, current.split(\':\')))\n\tnewH, newM = list(map(int, correct.spli
gauau
NORMAL
2022-04-03T04:07:59.396795+00:00
2022-04-03T04:11:39.335638+00:00
749
false
```\ndef convertTime(self, current: str, correct: str) -> int:\n\tans = 0\n\th, m = list(map(int, current.split(\':\')))\n\tnewH, newM = list(map(int, correct.split(\':\')))\n\td = 60*(newH - h) + newM - m\n\tfor x in [60, 15, 5, 1]:\n\t\tans += d//x\n\t\td %= x\n\treturn ans \n```
4
0
['Python', 'Python3']
1
minimum-number-of-operations-to-convert-time
javascript greedy 84ms
javascript-greedy-84ms-by-henrychen222-z7qd
Main idea: calculate minute difference, and divide 60, 15, 5, 1 respectively\n\nconst convertTime = (s, t) => {\n let [hs, ms] = op(s), [ht, mt] = op(t);\n
henrychen222
NORMAL
2022-04-03T04:04:37.080493+00:00
2022-04-03T04:05:56.176827+00:00
241
false
Main idea: calculate minute difference, and divide 60, 15, 5, 1 respectively\n```\nconst convertTime = (s, t) => {\n let [hs, ms] = op(s), [ht, mt] = op(t);\n let diff = Math.abs(hs * 60 + ms - (ht * 60 + mt));\n let res = 0;\n res += parseInt(diff / 60);\n diff %= 60;\n res += parseInt(diff / 15);\n diff %= 15;\n res += parseInt(diff / 5);\n diff %= 5;\n return res + diff; // finally diff will be in range [0, 4], use all 1\n};\n\nconst op = (s) => {\n let a = s.split(":").map(Number);\n return a;\n};\n```
4
0
['Greedy', 'JavaScript']
0
minimum-number-of-operations-to-convert-time
Simple Elegant Solution With Explaination
simple-elegant-solution-with-explainatio-0v93
Idea:\nFor simplification, we can firstly convert current and correct to minutes. In this problem, we essentially need to bridge the gap between current and cor
mrunankmistry52
NORMAL
2022-04-03T04:04:35.348149+00:00
2022-04-03T04:04:35.348176+00:00
291
false
## Idea:\nFor simplification, we can firstly convert `current` and `correct` to minutes. In this problem, we essentially need to bridge the gap between `current` and `correct` by adding `[1, 5, 15, 60]` minutes to `current`. To be precise, we need to add `correct - current` number of minutes to \'current\'. Let `diff = correct - current`.\n\n### Superincreasing sequence:\nNote that the sequence `[1, 5, 15, 60]` is a **superincreasing sequence**. A sequence is called superincreasing if every element of the sequence is greater than the sum of all previous elements in the sequence. In this case:\n```\n5 > 1\n15 > 1 + 5\n60 > 1 + 5 + 15\n```\n\nSince its superincreasing, we can **greedily** solve the problem by first subtracting 60 from `diff` as much as we can, then subtracting 15 as much as we can and so on until diff becomes zero. We simply count the number of times we have to subtract. We can implement this elegantly using python\'s `divmod`.\n\n### Solution:\n```\nclass Solution:\n def convertTime(self, current: str, correct: str) -> int:\n def get_time(t):\n hh, mm = t.split(\':\')\n return int(hh) * 60 + int(mm)\n \n current, correct = get_time(current), get_time(correct)\n operations = 0\n diff = correct - current\n \n for mins in [60, 15, 5, 1]:\n quotient, remainder = divmod(diff, mins)\n operations += quotient\n diff = remainder\n \n return operations\n```\n\n\nTime Complexity: O(1)\nSpace Complexity: O(1)\n\n**Do upvote if you like the solution. Have a nice day!**
4
0
['Python', 'Python3']
1
minimum-number-of-operations-to-convert-time
simple and easy C++ solution 😍❤️‍🔥
simple-and-easy-c-solution-by-shishirrsi-ehu4
\n# if it\'s help, please up \u2B06 vote! \u2764\uFE0F\n\n###### Let\'s Connect on LinkedIn: www.linkedin.com/in/shishirrsiam\n###### Let\'s Connect on Facebook
shishirRsiam
NORMAL
2024-08-16T01:27:32.138730+00:00
2024-08-16T01:27:32.138747+00:00
225
false
\n# if it\'s help, please up \u2B06 vote! \u2764\uFE0F\n\n###### Let\'s Connect on LinkedIn: www.linkedin.com/in/shishirrsiam\n###### Let\'s Connect on Facebook: www.fb.com/shishirrsiam\n\n\n\n# Complexity\n- Time complexity: O(D), where D is the difference in minutes between cur and target.\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int convertTime(string current, string correct) \n {\n int cur = stoi(current.substr(0, 2)) * 60; \n int target = stoi(correct.substr(0, 2)) * 60; \n cur += stoi(current.substr(3));\n target += stoi(correct.substr(3));\n \n int ans = 0;\n vector<int>useTime = {60, 15, 5, 1};\n while(cur != target)\n {\n for(auto time:useTime)\n {\n if(cur + time <= target)\n {\n cur += time;\n ans++;\n break;\n }\n }\n }\n return ans;\n }\n};\n```
3
0
['String', 'Greedy', 'C++']
3
minimum-number-of-operations-to-convert-time
Minimum Number of Operations to Convert Time Solution in C++
minimum-number-of-operations-to-convert-6ynpu
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
The_Kunal_Singh
NORMAL
2023-04-06T19:45:54.298037+00:00
2023-04-27T16:52:26.683109+00:00
207
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(n)\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(1)\n# Code\n```\nclass Solution {\npublic:\n int convertTime(string current, string correct) {\n int current_time=0, correct_time=0, diff, count=0;\n \n current_time = (int(current[0])*10+int(current[1]))*60+int(current[3])*10+int(current[4]);\n correct_time = (int(correct[0])*10+int(correct[1]))*60+int(correct[3])*10+int(correct[4]);\n\n diff = correct_time-current_time;\n while(diff!=0)\n {\n if(diff>=60)\n diff -= 60;\n else if(diff>=15)\n diff -= 15;\n else if(diff>=5)\n diff -= 5;\n else\n diff -= 1;\n count++;\n }\n return count;\n }\n};\n```\n![upvote new.jpg](https://assets.leetcode.com/users/images/792a2ee3-fa92-4936-9a87-216cd9a9ac02_1682613207.1269994.jpeg)
3
0
['C++']
0
minimum-number-of-operations-to-convert-time
Pyrhon3 | Simple | Beats 99.30% | Explained
pyrhon3-simple-beats-9930-explained-by-s-g0e9
The following code beats 99.30 % of python3 submissions\n\nclass Solution:\n def convertTime(self, current: str, correct: str) -> int:\n diff=(int(cor
shubhlaxh_porwal
NORMAL
2022-11-20T06:51:49.440496+00:00
2022-11-20T06:51:49.440533+00:00
15
false
The following code beats 99.30 % of python3 submissions\n```\nclass Solution:\n def convertTime(self, current: str, correct: str) -> int:\n diff=(int(correct[:2])*60)+int(correct[3:])-((int(current[:2])*60)+int(current[3:]))\n count=0\n while diff!=0:\n if diff>=60:\n diff-=60\n count+=1\n elif diff>=15:\n diff-=15\n count+=1\n elif diff>=5:\n diff-=5\n count+=1\n else:\n diff-=1\n count+=1\n return count\n```\nExplanation\nFirst we convert both the \'times\' into minutes by slicing the first 2 characters of the string and multiplying it by 60 to get the minutes and then adding the last two characters to get the total minutes python\nAfter doing this we subtract the two \'times\' two get the difference\nNow until the difference becomes 0 we keep subtracting 60 or 15 or 5 or 1 and incrementing the count for each subtraction
3
0
['Greedy']
1
minimum-number-of-operations-to-convert-time
Java Optimized From 8 ms to 1ms
java-optimized-from-8-ms-to-1ms-by-tbekp-z1hr
Solution 3 | 8ms | 11% time | 69% memory\n\nclass Solution {\n public int convertTime(String current, String correct) {\n int curHour = Integer.parseI
tbekpro
NORMAL
2022-11-08T06:44:26.717022+00:00
2022-11-08T06:58:48.774310+00:00
767
false
# Solution 3 | 8ms | 11% time | 69% memory\n```\nclass Solution {\n public int convertTime(String current, String correct) {\n int curHour = Integer.parseInt(current.charAt(0) + "" + current.charAt(1));\n int curMin = Integer.parseInt(current.charAt(3) + "" + current.charAt(4));\n int corHour = Integer.parseInt(correct.charAt(0) + "" + correct.charAt(1));\n int corMin = Integer.parseInt(correct.charAt(3) + "" + correct.charAt(4));\n int timeCur = curHour * 60 + curMin, timeCor = corHour * 60 + corMin;\n int count = 0;\n if (timeCur < timeCor) {\n while (timeCur != timeCor) {\n if (timeCur + 60 <= timeCor) {\n timeCur += 60;\n } else if (timeCur + 15 <= timeCor) {\n timeCur += 15;\n } else if (timeCur + 5 <= timeCor) {\n timeCur += 5;\n } else timeCur++;\n count++;\n }\n } else if (timeCur > timeCor) {\n while (timeCur != timeCor) {\n if (timeCur - 60 >= timeCor) {\n timeCur -= 60;\n } else if (timeCur - 15 >= timeCor) {\n timeCur -= 15;\n } else if (timeCur - 5 >= timeCor) {\n timeCur -= 5;\n } else timeCur--;\n count++;\n }\n }\n return count;\n }\n}\n```\nDecided to use StringBuilder.\n\n# Solution 2 | 2ms | 83% time | 87% memory\n```\nclass Solution {\n public int convertTime(String current, String correct) {\n StringBuilder sb = new StringBuilder();\n int curHour = Integer.parseInt(sb.append(current.charAt(0)).append(current.charAt(1)).toString());\n sb.setLength(0);\n int curMin = Integer.parseInt(sb.append(current.charAt(3)).append(current.charAt(4)).toString());\n sb.setLength(0);\n int corHour = Integer.parseInt(sb.append(correct.charAt(0)).append(correct.charAt(1)).toString());\n sb.setLength(0);\n int corMin = Integer.parseInt(sb.append(correct.charAt(3)).append(correct.charAt(4)).toString());\n int timeCur = curHour * 60 + curMin, timeCor = corHour * 60 + corMin;\n int count = 0;\n if (timeCur < timeCor) {\n while (timeCur != timeCor) {\n if (timeCur + 60 <= timeCor) {\n timeCur += 60;\n } else if (timeCur + 15 <= timeCor) {\n timeCur += 15;\n } else if (timeCur + 5 <= timeCor) {\n timeCur += 5;\n } else timeCur++;\n count++;\n }\n } else if (timeCur > timeCor) {\n while (timeCur != timeCor) {\n if (timeCur - 60 >= timeCor) {\n timeCur -= 60;\n } else if (timeCur - 15 >= timeCor) {\n timeCur -= 15;\n } else if (timeCur - 5 >= timeCor) {\n timeCur -= 5;\n } else timeCur--;\n count++;\n }\n }\n return count;\n }\n}\n```\n\n# Solution 1 | 1ms | 99% time |55% memory\nComplexity: O(1)\n```\nint curHour = (current.charAt(0) - \'0\') * 10 + (current.charAt(1) - \'0\');\n int curMin = (current.charAt(3) - \'0\') * 10 + (current.charAt(4) - \'0\');\n int corHour = (correct.charAt(0) - \'0\') * 10 + (correct.charAt(1) - \'0\');\n int corMin = (correct.charAt(3) - \'0\') * 10 + (correct.charAt(4) - \'0\');\n int diff = (corHour * 60 + corMin) - (curHour * 60 + curMin);\n int sixty = diff / 60;\n diff -= sixty * 60;\n int fifteen = diff / 15;\n diff -= fifteen * 15;\n int five = diff / 5;\n diff -= five * 5;\n return sixty + fifteen + five + diff;\n```
3
0
['Java']
0
minimum-number-of-operations-to-convert-time
c+ | 100% faster than all | easy
c-100-faster-than-all-easy-by-venomhighs-mkci
\n# Code\n\nclass Solution {\n int getTime(string &s) {\n return stoi(s.substr(0, 2)) * 60 + stoi(s.substr(3));\n }\npublic:\n int convertTime(s
venomhighs7
NORMAL
2022-10-02T16:24:19.971531+00:00
2022-10-02T16:24:19.971573+00:00
485
false
\n# Code\n```\nclass Solution {\n int getTime(string &s) {\n return stoi(s.substr(0, 2)) * 60 + stoi(s.substr(3));\n }\npublic:\n int convertTime(string current, string correct) {\n int diff = getTime(correct) - getTime(current), ops[4] = {60,15,5,1}, ans = 0;\n for (int op : ops) {\n ans += diff / op;\n diff %= op;\n }\n return ans;\n }\n};\n```
3
0
['C++']
0
minimum-number-of-operations-to-convert-time
Faster || Easy To Understand || C++ Code
faster-easy-to-understand-c-code-by-__kr-d5kv
Time Complexity : O(N)\n Space Complexity : O(1)*\n\n\nint convertTime(string current, string correct) {\n \n int hour1 = 0;\n \n ho
__KR_SHANU_IITG
NORMAL
2022-04-03T07:28:54.856988+00:00
2022-04-03T07:28:54.857021+00:00
253
false
* ***Time Complexity : O(N)***\n* ***Space Complexity : O(1)***\n\n```\nint convertTime(string current, string correct) {\n \n int hour1 = 0;\n \n hour1 = hour1 * 10 + current[0] - \'0\';\n \n hour1 = hour1 * 10 + current[1] - \'0\';\n \n int minute1 = 0;\n \n minute1 = minute1 * 10 + current[3] - \'0\';\n \n minute1 = minute1 * 10 + current[4] - \'0\';\n \n int hour2 = 0;\n \n hour2 = hour2 * 10 + correct[0] - \'0\';\n \n hour2 = hour2 * 10 + correct[1] - \'0\';\n \n int minute2 = 0;\n \n minute2 = minute2 * 10 + correct[3] - \'0\';\n \n minute2 = minute2 * 10 + correct[4] - \'0\';\n \n int time1 = hour1 * 60 + minute1;\n \n int time2 = hour2 * 60 + minute2;\n \n int count = 0;\n \n while(time1 + 60 <= time2)\n {\n count++;\n \n time1 += 60;\n }\n \n while(time1 + 15 <= time2)\n {\n count++;\n \n time1 += 15;\n }\n \n while(time1 + 5 <= time2)\n {\n count++;\n \n time1 += 5;\n }\n \n while(time1 + 1 <= time2)\n {\n count++;\n \n time1 += 1;\n }\n \n return count;\n }\n```
3
0
['Math', 'Greedy', 'C']
1
minimum-number-of-operations-to-convert-time
Python O(1) Time
python-o1-time-by-amlanbtp-kvgm
```\nclass Solution:\n def convertTime(self, s: str, c: str) -> int:\n dif=(int(c[:2])60+int(c[3:]))-(int(s[:2])60+int(s[3:]))\n count=0\n
amlanbtp
NORMAL
2022-04-03T04:05:38.753455+00:00
2022-04-03T04:05:38.753493+00:00
339
false
```\nclass Solution:\n def convertTime(self, s: str, c: str) -> int:\n dif=(int(c[:2])*60+int(c[3:]))-(int(s[:2])*60+int(s[3:]))\n count=0\n print(dif)\n arr=[60,15,5,1]\n for x in arr:\n count+=dif//x\n dif=dif%x\n return count
3
0
['Python', 'Python3']
1
minimum-number-of-operations-to-convert-time
python/java easy to understand
pythonjava-easy-to-understand-by-akaghos-fh2u
\tclass Solution:\n\t\tdef convertTime(self, current: str, correct: str) -> int:\n\t\t\tcurrentTime = int(current[0:2]) * 60 + int(current[3:])\n\t\t\tcorrectTi
akaghosting
NORMAL
2022-04-03T04:01:21.625440+00:00
2022-04-03T04:01:21.625487+00:00
227
false
\tclass Solution:\n\t\tdef convertTime(self, current: str, correct: str) -> int:\n\t\t\tcurrentTime = int(current[0:2]) * 60 + int(current[3:])\n\t\t\tcorrectTime = int(correct[0:2]) * 60 + int(correct[3:])\n\t\t\tdiff = correctTime - currentTime\n\t\t\tres = 0\n\t\t\tfor time in (60, 15, 5, 1):\n\t\t\t\tres += diff // time\n\t\t\t\tdiff %= time\n\t\t\treturn res\n\n\n\tclass Solution {\n\t\tpublic int convertTime(String current, String correct) {\n\t\t\tint currentTime = Integer.valueOf(current.substring(0, 2)) * 60 + Integer.valueOf(current.substring(3, 5));\n\t\t\tint correctTime = Integer.valueOf(correct.substring(0, 2)) * 60 + Integer.valueOf(correct.substring(3, 5));\n\t\t\tint diff = correctTime - currentTime;\n\t\t\tint res = 0;\n\t\t\tfor (int time: new int[] {60, 15, 5, 1}) {\n\t\t\t\tres += diff / time;\n\t\t\t\tdiff %= time;\n\t\t\t}\n\t\t\treturn res;\n\t\t}\n\t}
3
0
[]
0
minimum-number-of-operations-to-convert-time
leetcodedaybyday - Beats 100% with C++ and Python3
leetcodedaybyday-beats-100-with-c-and-py-5jwf
IntuitionThe problem requires determining the minimum number of operations needed to convert one time to another. The operations can only add fixed intervals (6
tuanlong1106
NORMAL
2024-12-25T09:00:03.349245+00:00
2024-12-25T09:00:03.349245+00:00
103
false
# Intuition The problem requires determining the minimum number of operations needed to convert one time to another. The operations can only add fixed intervals (60, 15, 5, or 1 minute). By leveraging the greedy algorithm, we can maximize the use of larger intervals first to minimize the total operations. # Approach 1. **Convert Time to Minutes**: - Both the `current` and `correct` times are converted to their total minutes since the start of the day. This simplifies calculations. 2. **Calculate the Difference**: - Compute the difference in minutes between `current` and `correct`. 3. **Greedy Algorithm**: - Use the largest possible time step (60, 15, 5, or 1) to cover the difference. - For each step: - Determine how many times the step can fit into the difference. - Reduce the difference by the amount covered. - Continue until the difference is 0. 4. **Return the Count**: - Sum up the operations needed for all steps and return the total. # Complexity - **Time Complexity**: - \(O(1)\): The algorithm performs a constant number of calculations, independent of input size. - **Space Complexity**: - \(O(1)\): Uses a fixed amount of space for variables and the steps list. --- # Code ```cpp [] class Solution { public: int convertTime(string current, string correct) { int cur = 60 * std::stoi(current.substr(0, 2)) + std::stoi(current.substr(3, 2)); int target = 60 * std::stoi(correct.substr(0, 2)) + std::stoi(correct.substr(3, 2)); int diff = target - cur; int count = 0; std::vector<int> steps = {60, 15, 5, 1}; for (int step : steps){ count += diff / step; diff %= step; } return count; } }; ``` ```python3 [] class Solution: def convertTime(self, current: str, correct: str) -> int: cur = 60 * int(current[:2]) + int(current[3:]) target = 60 * int(correct[:2]) + int(correct[3:]) diff = target - cur count = 0 steps = [60, 15, 5, 1] for step in steps: count += diff // step diff %= step return count ```
2
0
['C++', 'Python3']
0
minimum-number-of-operations-to-convert-time
Fastest Solution (Java)
fastest-solution-java-by-talhah20343-z8a3
Code\n\nclass Solution{\n public int convertTime(String current, String correct){\n int a = Integer.parseInt(current.substring(0, 2));\n int b
talhah20343
NORMAL
2023-07-28T17:43:39.568892+00:00
2023-07-28T17:43:39.568915+00:00
306
false
# Code\n```\nclass Solution{\n public int convertTime(String current, String correct){\n int a = Integer.parseInt(current.substring(0, 2));\n int b = Integer.parseInt(current.substring(3));\n int x = a*60+b;\n int c = Integer.parseInt(correct.substring(0, 2));\n int d = Integer.parseInt(correct.substring(3));\n int y = c*60+d;\n int k = y-x;\n int ans = 0;\n while(k>0){\n if(k%60==0){\n k -= 60;\n ans++;\n }\n else if(k%15==0){\n k -= 15;\n ans++;\n }\n else if(k%5==0){\n k -= 5;\n ans++;\n }\n else if(k%1==0){\n k -= 1;\n ans++;\n }\n }\n return ans;\n }\n}\n```
2
0
['Java']
0
minimum-number-of-operations-to-convert-time
Beat 99.29% 22ms Python3 easy solution
beat-9929-22ms-python3-easy-solution-by-mnx6x
\n# Code\n\nclass Solution:\n def convertTime(self, current: str, correct: str) -> int:\n current, correct = current.replace(\':\',\'\'), correct.repl
amitpandit03
NORMAL
2023-03-12T18:07:28.259422+00:00
2023-03-12T18:08:39.416014+00:00
240
false
\n# Code\n```\nclass Solution:\n def convertTime(self, current: str, correct: str) -> int:\n current, correct = current.replace(\':\',\'\'), correct.replace(\':\',\'\')\n a, count = (int(correct[:2]) * 60 + int(correct[2:])) - (int(current[:2]) * 60 + int(current[2:])), 0\n for i in [60, 15, 5, 1]:\n count += a // i\n a %= i\n return count \n\n #before for loop\n # while a != 0:\n # if a >= 60:\n # count += (a // 60)\n # a %= 60\n # elif 15 <= a < 60:\n # count += (a // 15)\n # a %= 15\n # elif 5 <= a < 15:\n # count += (a // 5)\n # a %= 5\n # elif 1 <= a < 5:\n # count += (a // 1)\n # a %= 1\n```
2
0
['String', 'Greedy', 'Python3']
0
minimum-number-of-operations-to-convert-time
Simple JAVA Solution || Greedy
simple-java-solution-greedy-by-prachiigo-w4wg
\nclass Solution {\n public int convertTime(String current, String correct) {\n int currentTimeInMin = getMinutes(current);\n int correctTimeIn
prachiigoyal
NORMAL
2022-09-23T15:50:20.455861+00:00
2022-09-23T15:50:20.455914+00:00
333
false
```\nclass Solution {\n public int convertTime(String current, String correct) {\n int currentTimeInMin = getMinutes(current);\n int correctTimeInMin = getMinutes(correct);\n \n int diff=correctTimeInMin-currentTimeInMin;\n int[] denominations={60,15,5,1};\n int count=0;\n if(diff>0){\n for(int denomination:denominations){\n if(diff%denomination==0){\n count+=diff/denomination;\n break;\n }else{\n count+=diff/denomination;\n diff=diff%denomination;\n }\n }\n }\n return count;\n }\n public int getMinutes(String time){\n int hours=Integer.parseInt(time.split(":")[0]);\n int minutes=Integer.parseInt(time.split(":")[1]);\n \n return hours*60+minutes;\n }\n}\n```
2
0
['Greedy', 'Java']
0
minimum-number-of-operations-to-convert-time
Easy Python solution
easy-python-solution-by-vistrit-fuxi
\ndef convertTime(self, current: str, correct: str) -> int:\n d=(int(correct[:2])*60+int(correct[3:]))-(int(current[:2])*60+int(current[3:]))\n re
vistrit
NORMAL
2022-06-04T13:48:52.731091+00:00
2022-06-04T13:48:52.731125+00:00
319
false
```\ndef convertTime(self, current: str, correct: str) -> int:\n d=(int(correct[:2])*60+int(correct[3:]))-(int(current[:2])*60+int(current[3:]))\n return d//60+(d%60)//15+((d%60)%15)//5+((d%60)%15)%5\n```
2
1
['Python', 'Python3']
0
minimum-number-of-operations-to-convert-time
Rust, parse(), %, O(n)
rust-parse-on-by-goodgoodwish-p97p
parse, unwrap_or.\n\n\nimpl Solution {\n pub fn convert_time(current: String, correct: String) -> i32 {\n let h = &current[..2].parse::<i32>().map_or(
goodgoodwish
NORMAL
2022-04-03T22:29:04.740069+00:00
2022-04-03T22:29:04.740106+00:00
60
false
parse, unwrap_or.\n\n```\nimpl Solution {\n pub fn convert_time(current: String, correct: String) -> i32 {\n let h = &current[..2].parse::<i32>().map_or(0, |x|x);\n let m = &current[3..].parse::<i32>().unwrap_or(0);\n let start = h*60 + m;\n\n let h = &correct[..2].parse::<i32>().map_or(0, |x|x);\n let m = &correct[3..].parse::<i32>().unwrap_or(0);\n let end = h*60 + m;\n let mut diff = end - start;\n \n let mut ans = diff/60;\n diff %= 60;\n ans += diff/15;\n diff %= 15;\n ans += diff/5;\n diff %= 5;\n ans += diff;\n \n // println!("h {}, m {}", h, m);\n \n ans\n }\n}\n```
2
0
['Rust']
0
minimum-number-of-operations-to-convert-time
[C++] || Convert given times to minutes and think in greedy way
c-convert-given-times-to-minutes-and-thi-mfzo
\nclass Solution {\npublic:\n int convertToMinutes(string current){\n int minutes = 0;\n //add hrs after converting to minutes 02:35 ->02*60 =
shm_47
NORMAL
2022-04-03T20:11:51.503586+00:00
2022-04-03T20:11:51.503614+00:00
81
false
```\nclass Solution {\npublic:\n int convertToMinutes(string current){\n int minutes = 0;\n //add hrs after converting to minutes 02:35 ->02*60 = 120\n int i;\n string hrs = "";\n for(i=0; i<=1; i++){\n hrs += current[i];\n }\n int hrI = stoi(hrs); //"02" -> 02\n minutes += (hrI*60); //02*60 -> 120\n \n string minute;\n for(i=3; i<=4; i++){\n minute += current[i];\n }\n int minuteI = stoi(minute);\n minutes += minuteI;\n \n return minutes;\n }\n \n int convertTime(string current, string correct) {\n int dest = convertToMinutes(current);\n int target = convertToMinutes(correct);\n \n int count = 0;\n while(dest != target){\n if(dest+60 <= target)\n dest += 60;\n else if(dest+15 <= target)\n dest += 15;\n else if(dest+5 <= target)\n dest += 5;\n else\n dest += 1;\n count++;\n }\n \n return count;\n }\n};\n```
2
0
['Greedy']
0
minimum-number-of-operations-to-convert-time
Java Greedy | Easy Understanding
java-greedy-easy-understanding-by-mudit1-wm9n
\nclass Solution {\n public int convertTime(String current, String correct) {\n // convert current time to minutes\n String[] current_time = cu
mudit19258
NORMAL
2022-04-03T09:27:53.716433+00:00
2022-04-03T09:27:53.716472+00:00
276
false
```\nclass Solution {\n public int convertTime(String current, String correct) {\n // convert current time to minutes\n String[] current_time = current.split(":");\n int current_hour = Integer.parseInt(current_time[0]);\n current_hour *= 60;\n int current_min = Integer.parseInt(current_time[1]);\n current_hour += current_min;\n \n // convert correct time to minutes\n String[] correct_time = correct.split(":");\n int correct_hour = Integer.parseInt(correct_time[0]);\n correct_hour *= 60;\n int correct_min = Integer.parseInt(correct_time[1]);\n correct_hour += correct_min;\n \n // operations\n int count = 0;\n \n // do greedily\n while(correct_hour - current_hour >= 60){\n count++;\n current_hour += 60;\n }\n while(correct_hour - current_hour >= 15){\n count++;\n current_hour += 15;\n }\n while(correct_hour - current_hour >= 5){\n count++;\n current_hour += 5;\n }\n while(correct_hour - current_hour >= 1){\n count++;\n current_hour += 1;\n }\n return count;\n }\n}\n```
2
0
['Greedy', 'Java']
1
minimum-number-of-operations-to-convert-time
C++ | Easy O(N) solution | maths
c-easy-on-solution-maths-by-yash2arma-pxoi
Please upvote if it helps :)\nCode:\n\nclass Solution {\npublic:\n int convertTime(string current, string correct) \n {\n int cur_hrs = stoi(curren
Yash2arma
NORMAL
2022-04-03T05:00:43.596001+00:00
2022-04-03T05:00:43.596035+00:00
175
false
**Please upvote if it helps :)**\n**Code:**\n```\nclass Solution {\npublic:\n int convertTime(string current, string correct) \n {\n int cur_hrs = stoi(current.substr(0,2)), cur_min = stoi(current.substr(3,4));\n int cor_hrs = stoi(correct.substr(0,2)), cor_min = stoi(correct.substr(3,4));\n\n int diff_min;\n int oper=0;\n \n //if minute diffrence is negative then we decrease correct hrs by 1 \n //Eg: current- 10:45, correct- 11:34 \n if((cor_min-cur_min) < 0) \n cor_hrs -= 1;\n \n diff_min = (60 + (cor_min - cur_min)) % 60; \n diff_min += 60*((24 + (cor_hrs - cur_hrs)) % 24); // mutliply by 60 to convert hrs into min.\n \n \n while(diff_min != 0)\n {\n if(diff_min >= 60)\n {\n diff_min -= 60; oper++;\n }\n else if(diff_min >= 15)\n {\n diff_min -= 15; oper++;\n }\n else if(diff_min >= 5)\n {\n diff_min -= 5; oper++;\n }\n else\n {\n diff_min -= 1; oper++;\n }\n }\n \n \n return oper; \n }\n};\n```\n**Please upvote if it helps :)**
2
0
['Math', 'String', 'C', 'C++']
0
minimum-number-of-operations-to-convert-time
Go / GoLang | Time: O(1) / 0 ms / 100% | Space: O(1) / 1.9 MB / 100%
go-golang-time-o1-0-ms-100-space-o1-19-m-qtfo
\nfunc convertTime(current string, correct string) int {\n currentHour, _ := strconv.Atoi(current[:2])\n correctHour, _ := strconv.Atoi(correct[:2])\n
aristorinjuang
NORMAL
2022-04-03T04:47:09.905790+00:00
2022-04-03T04:47:09.905853+00:00
138
false
```\nfunc convertTime(current string, correct string) int {\n currentHour, _ := strconv.Atoi(current[:2])\n correctHour, _ := strconv.Atoi(correct[:2])\n currentMinutes, _ := strconv.Atoi(current[3:])\n correctMinutes, _ := strconv.Atoi(correct[3:])\n result, minutes := 0, (correctHour - currentHour) * 60 - (currentMinutes - correctMinutes)\n \n for _, increase := range []int{60, 15, 5} {\n result += minutes / increase\n minutes %= increase\n }\n\n return result + minutes\n}\n```
2
0
['Greedy', 'Go']
0
minimum-number-of-operations-to-convert-time
[c++] || String || maths
c-string-maths-by-4byx-3eso
\nclass Solution {\npublic:\n int convertTime(string current, string correct) {\n int hd = stoi(correct.substr(0,2)) - stoi(current.substr(0,2));\n
4byx
NORMAL
2022-04-03T04:03:00.636340+00:00
2022-04-03T04:03:00.636388+00:00
212
false
```\nclass Solution {\npublic:\n int convertTime(string current, string correct) {\n int hd = stoi(correct.substr(0,2)) - stoi(current.substr(0,2));\n int ans = 0;\n ans += hd;\n \n int ct = stoi(correct.substr(3,2)) - stoi(current.substr(3,2));\n \n if(ct > 0){\n while(ct > 0){\n if(ct >= 15){\n ct -= 15;\n }else if(ct>=5){\n ct-=5;\n }\n else{\n ct-=1;\n }\n ans++;\n }\n }\n else if(ct < 0){\n int kk = ((hd-1)+24)%24;\n int td = 60+ct;\n while(td > 0){\n cout<<td<<" ";\n if(td >= 15){\n td -= 15;\n }else if(td>=5){\n td-=5;\n }\n else{\n td-=1;\n }\n kk++;\n }\n return kk;\n }\n return ans;\n }\n};\n```
2
0
[]
0
minimum-number-of-operations-to-convert-time
C++ Easy Understanding
c-easy-understanding-by-mayanksamadhiya1-xlka
\nclass Solution {\npublic:\n int convertTime(string current, string correct) \n {\n // extractig the minute & hours value from given strings\n
mayanksamadhiya12345
NORMAL
2022-04-03T04:01:09.768992+00:00
2022-04-03T04:01:09.769039+00:00
131
false
```\nclass Solution {\npublic:\n int convertTime(string current, string correct) \n {\n // extractig the minute & hours value from given strings\n int cur_hrs = stoi(current.substr(0,2));\n int cur_min = stoi(current.substr(3,4));\n int cor_hrs = stoi(correct.substr(0,2));\n int cor_min = stoi(correct.substr(3,4));\n \n // it will count the total number of minute difference\n int diff_min;\n int oper=0;\n \n // if our target is leeser than do -1\n if((cor_min-cur_min) < 0) \n cor_hrs -= 1;\n \n // counting the diff min \n // first for minutes and then for hours (1 hour = 60 minute)\n diff_min = (60 + (cor_min - cur_min)) % 60;\n diff_min += 60*((24 + (cor_hrs - cur_hrs)) % 24);\n \n // while our diff min is not equal to 0\n while(diff_min != 0)\n {\n // if our diff is bigger than or equal to 60 than substract 60 from it \n if(diff_min >= 60)\n {\n diff_min -= 60; \n oper++;\n }\n // if our diff is bigger than or equal to 15 than substract 15 from it \n else if(diff_min >= 15)\n {\n diff_min -= 15; \n oper++;\n }\n // if our diff is bigger than or equal to 5 than substract 5 from it \n else if(diff_min >= 5)\n {\n diff_min -= 5; \n oper++;\n }\n // if our diff is bigger than or equal to 1 than substract 1 from it \n else\n {\n diff_min -= 1; \n oper++;\n }\n }\n \n \n return oper; \n }\n};\n```
2
0
[]
0
minimum-number-of-operations-to-convert-time
Python 1-liner
python-1-liner-by-shreyansh94-vyk6
Algorithm:\n1. Split the strings at : and convert each element to int().\n2. If correct time minutes is less than current time minutes, subtract 1 from correct
shreyansh94
NORMAL
2022-04-03T04:00:49.052888+00:00
2022-04-03T04:02:39.467200+00:00
245
false
Algorithm:\n1. Split the strings at `:` and convert each element to `int()`.\n2. If `correct` time minutes is `less` than `current` time minutes, `subtract 1` from `correct` time hours and `add 60` to `correct` time minutes.\n3. return `difference` between the time hours `plus` the number of operation to make `correct` time minutes which can be calculated by `dividing` the difference in minutes by `15`, `5` and `1` respectively.\n\n```\nclass Solution(object):\n def convertTime(self, cu, co):\n return ((lambda x : (x[2] - x[0])+ (x[3]-x[1])//15 + ((x[3]-x[1])%15)//5 + ((x[3]-x[1])%15)%5)((lambda a, b, c, d : [a, b, c-1, d+60] if d < b else [a, b, c, d])(int(cu.split(\':\')[0]), int(cu.split(\':\')[1]),int(co.split(\':\')[0]), int(co.split(\':\')[1]))))\n```
2
1
['Python']
0
minimum-number-of-operations-to-convert-time
Easy Java Solution in O(1) Time complexity
easy-java-solution-in-o1-time-complexity-5lpi
IntuitionWe are given two time strings (current and correct) in the format "HH:mm", and we need to determine the minimum number of operations to convert the cur
vivekvinay96254
NORMAL
2025-02-18T14:01:14.135638+00:00
2025-02-18T14:01:14.135638+00:00
89
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> We are given two time strings (current and correct) in the format "HH:mm", and we need to determine the minimum number of operations to convert the current time to the correct time. Each operation can be one of the following: Add 60 minutes (1 hour), Add 15 minutes, Add 5 minutes, Add 1 minute. To solve this, we will first convert both the current and correct times into the total number of minutes since midnight. Then, we calculate the difference in minutes between correct and current, which will give us the total amount of time we need to add. After that, we will try to minimize the number of operations by using the largest units first (i.e., 60 minutes, then 15 minutes, then 5 minutes, and finally 1 minute). # Approach <!-- Describe your approach to solving the problem. --> Convert Time to Minutes: Convert both current and correct times from the "HH:mm" format to the total number of minutes since midnight. For current and correct time, the calculation is done as: HH * 60 + mm where HH is the hour and mm is the minute. Calculate the Difference: Subtract the number of minutes of current from correct to get the difference rem. This is the total number of minutes we need to adjust the time by. Minimize Operations: Start with the largest possible operation (60 minutes). Divide rem by 60 to get how many times we can apply this operation. Then, use 15 minutes, 5 minutes, and finally 1 minute to account for the remainder. Count each operation and return the total number of operations. # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> O(1) - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> O(1) # Code ```java [] class Solution { public int convertTime(String current, String correct) { int present = 0; int fixed = 0; // Convert current time to minutes present += (current.charAt(0) - '0') * 10 * 60; present += (current.charAt(1) - '0') * 60; present += (current.charAt(3) - '0') * 10; present += (current.charAt(4) - '0'); // Convert correct time to minutes fixed += (correct.charAt(0) - '0') * 10 * 60; fixed += (correct.charAt(1) - '0') * 60; fixed += (correct.charAt(3) - '0') * 10; fixed += (correct.charAt(4) - '0'); // Calculate the difference in minutes int rem = fixed - present; int res = 0; // Use 60 minutes operation first res += rem / 60; rem = rem % 60; // Then use 15 minutes operation res += rem / 15; rem = rem % 15; // Then use 5 minutes operation res += rem / 5; rem = rem % 5; // Finally use 1 minute operation res += rem / 1; rem = rem % 1; return res; } } ```
1
0
['Java']
0
minimum-number-of-operations-to-convert-time
2D-dp - java
2d-dp-java-by-kartheek_gurram-m3cj
Intuition\n Describe your first thoughts on how to solve this problem. \nDP-Unbounded knapsack approach\n\n# Approach\n Describe your approach to solving the pr
kartheek_gurram
NORMAL
2024-10-21T13:54:54.507401+00:00
2024-10-21T13:54:54.507428+00:00
17
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nDP-Unbounded knapsack approach\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```java []\nclass Solution {\n public int convertTime(String current, String correct) {\n int currMinutes = Integer.parseInt(current.substring(0,2))*60 + Integer.parseInt(current.substring(3,5));\n int corrMinutes = Integer.parseInt(correct.substring(0,2))*60 + Integer.parseInt(correct.substring(3,5));\n int diff = corrMinutes - currMinutes;\n int operations[] = {1,5,15,60};\n int n = operations.length;\n int dp[][] = new int[n+1][diff+1];\n for(int j=1;j<=diff;j++) {\n dp[0][j] = Integer.MAX_VALUE - 1;\n }\n for(int i=1;i<n+1;i++) {\n for(int j=0;j<diff+1;j++) {\n if(operations[i-1]<=j) {\n dp[i][j] = Math.min(dp[i-1][j], 1 + dp[i][j-operations[i-1]]);\n } else {\n dp[i][j] = dp[i-1][j];\n }\n }\n }\n return dp[n][diff];\n }\n}\n```
1
0
['Dynamic Programming', 'Java']
0
minimum-number-of-operations-to-convert-time
Easy 100% beats💯💯💯👍🏻👍🏻
easy-100-beats-by-israatumeh9-st72
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
israatumeh9
NORMAL
2024-09-25T17:43:08.291256+00:00
2024-09-25T17:43:08.291280+00:00
46
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\npublic:\n int convertTime(string current, string correct) {\n int ans=0;\n int n1=stoi(current.substr(0,2));\n n1*=60;\n int n2=stoi(current.substr(3,2));\n int sum1=n1+n2;\n int n3=stoi(correct.substr(0,2));\n int n4=stoi(correct.substr(3,2));\n int sum2=(n3*60)+n4;\n int sum=abs(sum1-sum2);\n while(sum>=60){\n ans++;\n sum-=60;\n }\n while(sum>=15){\n ans++;\n sum-=15;\n }\n while(sum>=5){\n ans++;\n sum-=5;\n }\n while(sum>=1){\n ans++;\n sum--;\n }\n return ans;\n }\n};\n```
1
0
['C++']
0
minimum-number-of-operations-to-convert-time
2224 Easy Java Solution
2224-easy-java-solution-by-roger2023-o24k
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
roger2023
NORMAL
2024-07-27T14:26:59.527644+00:00
2024-07-27T14:26:59.527666+00:00
189
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public int convertTime(String current, String correct) {\n String[] cur = current.split(":");\n String[] cor = correct.split(":");\n\n int[] a = {Integer.parseInt(cur[0]), Integer.parseInt(cur[1])};\n int[] b = {Integer.parseInt(cor[0]), Integer.parseInt(cor[1])};\n\n int curMinutes = (a[0] * 60) + a[1];\n int corMinutes = (b[0] * 60) + b[1];\n\n int diff = Math.abs(corMinutes - curMinutes);\n\n if (curMinutes > corMinutes)\n diff = (24 * 60) - diff;\n\n int ops = diff / 60;\n int rem = diff % 60;\n ops += rem / 15;\n rem = rem % 15;\n ops += rem / 5;\n rem = rem % 5;\n ops += rem / 1;\n\n return ops;\n }\n}\n```
1
0
['Array', 'String', 'Java']
2
minimum-number-of-operations-to-convert-time
Recursive JS Solution to Convert Time With Minimal Steps
recursive-js-solution-to-convert-time-wi-eary
Intuition\nThe problem requires converting a given current time to a correct time using the fewest number of operations, where each operation can increase the t
OscarQ5
NORMAL
2024-06-30T22:15:32.685890+00:00
2024-06-30T22:15:32.685907+00:00
45
false
# Intuition\nThe problem requires converting a given current time to a correct time using the fewest number of operations, where each operation can increase the time by 1, 5, 15, or 60 minutes. To solve, we can convert both current and correct times to total minutes and then calculate the difference. The difference is then reduced by the largest operation possible until the difference is zero.\n\n# Approach\n**Base conversion** - Convert both current and correct times from \'HH:MM\' format to total minutes.\n\n**Calculate difference** - Calculate difference in total minutes and find the number of operations needed. \n\n**Find min operations** - Initialize operations variable to count the number of operations needed to reduce the difference to zero. While the difference is greater than zero, subtract the largest operation possible until the difference is zero.\n\n**Return operations** - Return the number of operations needed. \n\n# Complexity\n- Time complexity:\n*O(n)* - This is because we convert time to minutes and for the minOperations function, where *n* is the number of operations needed in the worst case.\n\n- Space complexity:\n*O(1)* - This is because we only use a constant amount of extra space for variables.\n\n# Code\n```\n/**\n * @param {string} current\n * @param {string} correct\n * @return {number}\n */\nvar convertTime = function (current, correct) {\n //Convert current/correct time from \'HH:MM\' format to total minutes\n const currentMinutes = parseInt(current.slice(0, 2)) * 60 + parseInt(current.slice(3, 5));\n const correctMinutes = parseInt(correct.slice(0, 2)) * 60 + parseInt(correct.slice(3, 5));\n\n //Calculate the difference in minutes and find the number of operations\n return minOperations(correctMinutes - currentMinutes)\n};\n\nfunction minOperations(difference) {\n //Initialize counter for the number of operations\n let operations = 0;\n //Loop until the difference is zero\n while (difference > 0) {\n //If the difference is greater than or equal to 60, subtract from the difference and increment operations count\n if (difference >= 60) {\n difference -= 60;\n operations++;\n //If the difference is greater than or equal to 15, subtract from the difference and increment operations count\n } else if (difference >= 15) {\n difference -= 15;\n operations++;\n //If the difference is greater than or equal to 5, subtract from the difference and increment operations count\n } else if (difference >= 5) {\n difference -= 5;\n operations++;\n //If the difference is less than 5, subtract 1 and increment the operation count\n } else {\n difference--;\n operations++;\n }\n }\n //Return the number of operations needed\n return operations;\n};\n```
1
0
['JavaScript']
0
minimum-number-of-operations-to-convert-time
Simple java code 1 ms beats 89.73 %
simple-java-code-1-ms-beats-8973-by-arob-o33o
\n# Complexity\n\n# Code\n\nclass Solution {\n public int convertTime(String current, String correct) {\n int a = Integer.parseInt(current.substring(0
Arobh
NORMAL
2024-03-25T03:10:37.823708+00:00
2024-03-25T03:10:37.823741+00:00
97
false
\n# Complexity\n![image.png](https://assets.leetcode.com/users/images/dce0a3e7-2468-41e2-9e18-8dfce639a2dd_1711336215.8592305.png)\n# Code\n```\nclass Solution {\n public int convertTime(String current, String correct) {\n int a = Integer.parseInt(current.substring(0,2))*60 + Integer.parseInt(current.substring(3));\n int b = Integer.parseInt(correct.substring(0,2))*60 + Integer.parseInt(correct.substring(3));\n int diff = b-a;\n int c60 = diff/60;\n diff %= 60;\n int c15 = diff/15;\n diff %= 15;\n int c5 = diff/5;\n diff %= 5;\n return c60+c15+c5+diff;\n }\n}\n```
1
0
['String', 'Greedy', 'Java']
0
minimum-number-of-operations-to-convert-time
Java solutoin Beats 94% easy to understand
java-solutoin-beats-94-easy-to-understan-02ie
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
Ali-Aljufairi
NORMAL
2023-11-05T06:34:44.078880+00:00
2023-11-05T06:34:44.078909+00:00
267
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public int convertTime(String current, String correct) {\n int currentTime = timeToMinutes(current);\n int correctTime = timeToMinutes(correct);\n int timeDifference = Math.abs(currentTime - correctTime);\n \n int ans = 0;\n int[] timeReductions = {60, 15, 5, 1};\n \n for (int reduction : timeReductions) {\n while (timeDifference >= reduction) {\n ans += timeDifference / reduction;\n timeDifference %= reduction;\n }\n }\n \n return ans;\n }\n\n private int timeToMinutes(String time) {\n int hours = Integer.parseInt(time.substring(0, 2));\n int minutes = Integer.parseInt(time.substring(3));\n return hours * 60 + minutes;\n }\n}\n\n```
1
0
['Java']
0
minimum-number-of-operations-to-convert-time
Short and simple: convert to minutes
short-and-simple-convert-to-minutes-by-s-6duk
Complexity\n- Time complexity: O(n)\n- Space complexity: O(1)\n\n# Code\n\nvar convertTime = function(current, correct) {\n const steps = [60, 15, 5, 1];\n
stuymedova
NORMAL
2023-09-25T08:42:47.226729+00:00
2023-09-25T08:42:47.226755+00:00
8
false
# Complexity\n- Time complexity: $$O(n)$$\n- Space complexity: $$O(1)$$\n\n# Code\n```\nvar convertTime = function(current, correct) {\n const steps = [60, 15, 5, 1];\n const currentTimeInMinutes = convertToMinutes(current);\n const correctTimeInMinutes = convertToMinutes(correct);\n let diff = correctTimeInMinutes - currentTimeInMinutes;\n let operationsCount = 0;\n\n for (const step of steps) {\n const currentStepsCount = Math.floor(diff / step);\n operationsCount += currentStepsCount;\n diff -= currentStepsCount * step;\n if (diff === 0) break;\n }\n return operationsCount;\n};\n\nfunction convertToMinutes(time) {\n const [hours, minutes] = Array.from(time.split(\':\'), Number);\n return hours * 60 + minutes;\n}\n```
1
0
['JavaScript']
0
minimum-number-of-operations-to-convert-time
✅✔️100% Beat || Easy to understand C++ Solution || Greedy ✈️✈️✈️✈️✈️
100-beat-easy-to-understand-c-solution-g-wxlr
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
ajay_1134
NORMAL
2023-06-22T07:43:20.132762+00:00
2023-06-22T07:43:20.132782+00:00
311
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int convertTime(string s1, string s2) {\n int h1 = stoi(s1.substr(0,2));\n int m1 = stoi(s1.substr(3,2));\n int h2 = stoi(s2.substr(0,2));\n int m2 = stoi(s2.substr(3,2));\n int hrDiff = h2 - h1;\n if(hrDiff < 0) hrDiff += 24;\n int minDiff = m2 - m1;\n int total = hrDiff*60 + minDiff;\n int ans = 0;\n\n if(total >= 60){\n ans += (total/60);\n total = total%60;\n }\n if(total >= 15){\n ans += (total/15);\n total = total%15;\n }\n if(total >= 5){\n ans += (total / 5);\n total = total%5;\n }\n ans += total;\n return ans;\n \n }\n};\n```
1
0
['String', 'Greedy', 'C++']
1
minimum-number-of-operations-to-convert-time
Easy || C++
easy-c-by-priya0498-wfbr
```\nclass Solution {\npublic:\n int convertTime(string current, string correct) {\n \n int currentHours = 0;\n int currentMinute = 0;\n
priya0498
NORMAL
2023-06-03T08:26:28.490730+00:00
2023-06-03T08:26:28.490760+00:00
10
false
```\nclass Solution {\npublic:\n int convertTime(string current, string correct) {\n \n int currentHours = 0;\n int currentMinute = 0;\n int correctHours = 0;\n int correctMinute = 0; \n \n int i = 0;\n \n while(current[i] != \':\') {\n currentHours = currentHours * 10 + (current[i] - \'0\');\n ++i;\n } \n ++i;\n while(i < current.size()) {\n currentMinute = currentMinute * 10 + (current[i] - \'0\');\n ++i;\n }\n \n int j = 0;\n while(correct[j] != \':\') {\n correctHours = correctHours * 10 + (correct[j] - \'0\');\n ++j;\n }\n ++j;\n while(j < correct.size()) {\n correctMinute = correctMinute * 10 + (correct[j] - \'0\');\n ++j;\n }\n \n currentMinute += currentHours * 60;\n correctMinute += correctHours * 60;\n vector<int> minutes = {60, 15, 5, 1};\n \n int count = 0;\n \n for(int i = 0; i < 4; ++i) {\n \n int minute = minutes[i];\n while(currentMinute < correctMinute) {\n currentMinute += minute;\n count++;\n }\n\n if(currentMinute == correctMinute) {\n return count;\n }\n\n currentMinute -= minute;\n count--;\n }\n \n return 0;\n }\n};
1
0
[]
0
minimum-number-of-operations-to-convert-time
Swift 100% time complexity
swift-100-time-complexity-by-adamsmsher-nmxf
Intuition\nFigure out how to get the difference. \nUse minutes because its the units used per operation.\n\n# Approach\nConvert to minutes, get difference, divi
AdamSmsher
NORMAL
2022-11-04T22:39:28.740773+00:00
2022-11-04T22:42:49.261774+00:00
65
false
# Intuition\nFigure out how to get the difference. \nUse minutes because its the units used per operation.\n\n# Approach\nConvert to minutes, get difference, divide remaining by minutes\n\n# Complexity\n- Time complexity:\no(n)\n\n- Space complexity:\no(n)\n\n# Code\n```\nclass Solution {\n func convertTime(_ current: String, _ correct: String) -> Int {\n var current = current.components(separatedBy: ":").map{ Int(String($0))! }\n var correct = correct.components(separatedBy: ":").map{ Int(String($0))! }\n current[0] *= 60; correct[0] *= 60\n var remainder = abs(current.reduce(0, +) - correct.reduce(0, +))\n var res = 0\n \n res += remainder / 60\n remainder %= 60\n\n res += remainder / 15\n remainder %= 15 \n\n res += remainder / 5 \n remainder %= 5\n\n res += remainder\n\n return res\n }\n}\n```
1
0
['Swift']
1
minimum-number-of-operations-to-convert-time
Minimum memory || 81% faster MATH INTEGER
minimum-memory-81-faster-math-integer-by-wmh7
Clean code and faster!\n\n\n\n\nclass Solution {\n public int convertTime(String current, String correct) {\n int x = Integer.parseInt(current.substri
Dilshod_Rich
NORMAL
2022-10-27T12:30:41.013936+00:00
2022-10-27T12:30:41.013974+00:00
36
false
Clean code and faster!\n\n\n\n\nclass Solution {\n public int convertTime(String current, String correct) {\n int x = Integer.parseInt(current.substring(0,2));\n int y = Integer.parseInt(correct.substring(0,2));\n\n int x1 = Integer.parseInt(current.substring(3));\n int x2 = Integer.parseInt(correct.substring(3));\n\n int z = x2-x1;\n if(x2<x1){\n y=y-1;\n z = 60 - x1+x2;\n }\n int a = (z/15);\n int b = ((z-a*15)/5);\n int c = z-a*15-b*5;\n\n return y-x+a+b+c;\n \n }\n}
1
0
['Math', 'Java']
0
minimum-number-of-operations-to-convert-time
c++||Manual code||100% faster
cmanual-code100-faster-by-nikhil909-exuy
class Solution {\npublic\n\n//we can also use substr() and stoi() functions here ,I have done that manually coz given string wasn\'t so complex\n\n int toMi
nikhil909
NORMAL
2022-10-14T19:56:56.086943+00:00
2022-10-14T20:02:55.827664+00:00
357
false
class Solution {\npublic\n\n//we can also use substr() and stoi() functions here ,I have done that manually coz given string wasn\'t so complex\n\n int toMinute(string curr){\n int mi=0; \n mi=mi+curr[0]-\'0\'; mi*=10;\n mi=mi+curr[1]-\'0\';\n mi*=60;\n int a=0;\n a=a+curr[3]-\'0\'; a*=10;\n a=a+curr[4]-\'0\';\n mi+=a;\n return mi;\n }\n int convertTime(string curr, string correct) {\n int a=toMinute(curr);\n int b=toMinute(correct);\n int count=0;\n while(a<b){\n if(b-a>=60){\n a+=60;\n }\n else if(b-a>=15){\n a+=15;\n }\n else if(b-a>=5){\n a+=5;\n }\n else {\n a+=1;\n }\n count++; \n }\n return count;\n }\n};
1
0
['C', 'C++']
1
minimum-number-of-operations-to-convert-time
100% fast (convert into min)
100-fast-convert-into-min-by-bhutanibhan-dzcx
upvote\n\n int convertTime(string cur, string cor) {\n int curr = ((cur[0]-\'0\')*10+cur[1]-\'0\')*60+(cur[3]-\'0\')*10+cur[4]-\'0\';\n int cor
bhutanibhanu
NORMAL
2022-09-29T02:03:03.705207+00:00
2022-09-29T02:03:03.705253+00:00
402
false
upvote\n```\n int convertTime(string cur, string cor) {\n int curr = ((cur[0]-\'0\')*10+cur[1]-\'0\')*60+(cur[3]-\'0\')*10+cur[4]-\'0\';\n int corr = ((cor[0]-\'0\')*10+cor[1]-\'0\')*60+(cor[3]-\'0\')*10+cor[4]-\'0\';\n int ops =0, rem=corr-curr;\n while(rem>=60){\n rem -= 60;\n ops++;\n }\n while(rem>=15){\n rem -= 15;\n ops++;\n }\n while(rem>=5){\n rem -= 5;\n ops++;\n }\n while(rem>=1){\n rem -= 1;\n ops++;\n }\n \n return ops;\n }\n```
1
0
['C']
0
minimum-number-of-operations-to-convert-time
Easiest Shortest Simplest C++ solution
easiest-shortest-simplest-c-solution-by-i7x46
Convert the strings to int time in minutes and then find the difference. Apply simple maths!\n\n\tclass Solution {\n\tpublic:\n\t\tint convertTime(string curren
ansh1701
NORMAL
2022-09-14T17:53:36.658499+00:00
2022-09-14T17:57:20.507344+00:00
256
false
Convert the strings to int time in minutes and then find the difference. Apply simple maths!\n\n\tclass Solution {\n\tpublic:\n\t\tint convertTime(string current, string correct) {\n\t\t\tint ftime = (stoi(current.substr(0,2))) * 60 + (stoi(current.substr(3,current.size())));\n\t\t\tint ltime = (stoi(correct.substr(0,2))) * 60 + (stoi(correct.substr(3,correct.size())));\n\t\t\tint diff = ltime - ftime;\n\t\t\tint ans=0;\n\t\t\tans += diff/60;\n\t\t\tdiff = diff%60;\n\t\t\tans += diff/15;\n\t\t\tdiff = diff%15;\n\t\t\tans +=diff/5;\n\t\t\tdiff = diff%5;\n\t\t\tans += diff;\n\t\t\treturn ans;\n\t\t}\n\t};
1
0
['C']
0
minimum-number-of-operations-to-convert-time
C++ | Easily Understandable | Brute-Force | Greedy
c-easily-understandable-brute-force-gree-obds
\nTime: O(Log minute) Space: O(1)\n\nclass Solution {\npublic:\n int convertTime(string current, string correct) {\n int m1=10*(current[3]-\'0\')+(cu
silicon_
NORMAL
2022-08-18T16:38:45.083760+00:00
2022-08-18T16:38:45.083809+00:00
118
false
```\nTime: O(Log minute) Space: O(1)\n\nclass Solution {\npublic:\n int convertTime(string current, string correct) {\n int m1=10*(current[3]-\'0\')+(current[4]-\'0\'),\n m2=10*(correct[3]-\'0\')+(correct[4]-\'0\');\n int k=m2-m1;\n int h1=10*(current[0]-\'0\')+(current[1]-\'0\'),\n h2=10*(correct[0]-\'0\')+(correct[1]-\'0\');\n int k2=h2-h1;\n int tmin=k2*60+k;\n k=0;\n while(tmin){\n if(tmin>=60){\n k+=tmin/60;tmin%=60;\n }else if(tmin>=15)\n k+=tmin/15,tmin%=15;\n else if(tmin>=5)\n k+=tmin/5,tmin%=5;\n else\n k+=tmin/1,tmin%=1;\n }\n return k;\n }\n};\n```
1
0
['Greedy', 'C']
0
minimum-number-of-operations-to-convert-time
100% Faster C++ Solution || Easy to understand
100-faster-c-solution-easy-to-understand-se23
\nclass Solution {\npublic:\n int convertTime(string current, string correct) {\n int hours1=stoi(current.substr(0,2));\n int hours2=stoi(corre
sticktrick3181
NORMAL
2022-08-11T20:51:53.126160+00:00
2022-08-11T20:51:53.126190+00:00
200
false
```\nclass Solution {\npublic:\n int convertTime(string current, string correct) {\n int hours1=stoi(current.substr(0,2));\n int hours2=stoi(correct.substr(0,2));\n int min1=stoi(current.substr(3,2));\n int min2=stoi(correct.substr(3,2));\n int mins=((60-min1)+(min2))<60?abs((hours2-hours1-1)*60)+((60-min1)+(min2)):abs((hours2-hours1)*60) + abs(min2-min1);\n int count=0;\n while(mins!=0){\n if(mins>=60){\n count++;mins-=60;\n }\n else if(mins>=15){\n count++;mins-=15;\n }\n else if(mins>=5){\n count++;mins-=5;\n }\n else if(mins>=1){\n count++;mins-=1;\n }\n }\n return count;\n \n }\n};\n```\n![image](https://assets.leetcode.com/users/images/b615f4cb-50ff-4548-910e-aef09b4f7f28_1660251060.0716007.png)\n
1
0
['C++']
0
minimum-number-of-operations-to-convert-time
C++ (0ms) and Java (1ms) | Easy Understanding
c-0ms-and-java-1ms-easy-understanding-by-7w7b
C++ Solution\n\nclass Solution {\npublic:\n int convertTime(string current, string correct) {\n int ret=0, digit=1, cur=0, cor=0, hour=1, i;\n
keremtan
NORMAL
2022-08-10T12:41:51.332240+00:00
2022-08-10T12:41:51.332286+00:00
202
false
**C++ Solution**\n```\nclass Solution {\npublic:\n int convertTime(string current, string correct) {\n int ret=0, digit=1, cur=0, cor=0, hour=1, i;\n int t[] = {59,14,4,0};\n for(i = current.size()-1; i>-1; i--){\n if(58!=current[i]){\n cur += (current[i]-48)*digit*hour;\n cor += (correct[i]-48)*digit*hour;\n digit=10;\n }\n else {\n digit=1;\n hour=60;\n }\n }\n cor -= cur;\n i=0;\n while(cor>0){\n if(cor>t[i]){\n cor -= t[i]+1;\n ret++;\n }\n else i++;\n } \n return ret;\n }\n};\n```\n**Java Solution**\n```\nclass Solution {\n public int convertTime(String current, String correct) {\n int ret=0, digit=1, cur=0, cor=0, hour=1, i;\n int[] t = {59,14,4,0};\n for(i = current.length()-1; i>-1; i--){\n if(58!=current.charAt(i)){\n cur += (current.charAt(i)-48)*digit*hour;\n cor += (correct.charAt(i)-48)*digit*hour;\n digit=10;\n }\n else {\n digit=1;\n hour=60;\n }\n }\n cor -= cur;\n i=0;\n while(cor>0){\n if(cor>t[i]){\n cor -= t[i]+1;\n ret++;\n }\n else i++;\n } \n return ret;\n }\n}\n```
1
0
['C', 'Java']
0
minimum-number-of-operations-to-convert-time
Easiest Java Solution | T=O(1), S=O(1)
easiest-java-solution-to1-so1-by-ayushi9-20wz
\n\n\n\npublic int convertTime(String current, String correct) {\n String[] start = current.split(":");\n int startMins = Integer.valueOf(start[0]
ayushi9
NORMAL
2022-08-03T10:54:52.818725+00:00
2022-08-03T10:54:52.818752+00:00
124
false
\n\n\n```\npublic int convertTime(String current, String correct) {\n String[] start = current.split(":");\n int startMins = Integer.valueOf(start[0])*60+Integer.valueOf(start[1]);\n \n String[] target = correct.split(":");\n int targetMins = Integer.valueOf(target[0])*60+Integer.valueOf(target[1]);\n\n int diff = targetMins-startMins;\n int ops=0;\n \n ops += diff/60; \n diff = diff%60;\n\n ops += diff/15;\n diff = diff%15;\n \n ops += diff/5;\n diff = diff%5;\n \n return ops + diff;\n }\n```
1
0
['Java']
0
minimum-number-of-operations-to-convert-time
Greedy || 100% Faster ||0ms
greedy-100-faster-0ms-by-hs873251-rrqv
\nclass Solution {\npublic:\n int convertTime(string current, string correct) {\n int res=0;\n string ans=current.substr(0,2);\n string
hs873251
NORMAL
2022-07-29T03:30:18.056751+00:00
2022-07-29T03:30:18.056777+00:00
192
false
```\nclass Solution {\npublic:\n int convertTime(string current, string correct) {\n int res=0;\n string ans=current.substr(0,2);\n string ans1=current.substr(3,5);\n int a1=stoi(ans)*60;\n int a2=stoi(ans1);\n string st=correct.substr(0,2);\n string st1=correct.substr(3,5);\n int b1=stoi(st)*60;\n int b2=stoi(st1);\n \n int ff=abs((a1+a2)-(b1+b2));\n int hours = ff/60;\n res+=hours;\n int minutes=ff%60;\n if(minutes % 15 ==0 ){\n res+=minutes/15;\n return res;\n }\n if(minutes > 15 ){\n res+=minutes/15;\n minutes = minutes%15;\n }\n \n if(minutes%5==0){\n res+=minutes/5;\n return res;\n }\n if(minutes > 5){\n res+=minutes/5;\n minutes=minutes%5;\n }\n res+=minutes;\n return res;\n return 0;\n }\n};\n```
1
0
['Greedy', 'C', 'C++']
0
minimum-number-of-operations-to-convert-time
[LeetCode The Hard Way] Greedy || Explanation
leetcode-the-hard-way-greedy-explanation-5efq
Please check out LeetCode The Hard Way for more solution explanations and tutorials. If you like it, please give a star and watch my Github Repository.\n\n---\n
__wkw__
NORMAL
2022-07-19T14:58:04.771797+00:00
2022-07-19T15:02:36.144535+00:00
124
false
Please check out [LeetCode The Hard Way](https://wingkwong.github.io/leetcode-the-hard-way/) for more solution explanations and tutorials. If you like it, please give a star and watch my [Github Repository](https://github.com/wingkwong/leetcode-the-hard-way).\n\n---\n\nChoosing `60` 1 time is better than choosing `15` 4 times. We choose from the largest number as many times as we could, then choose the second largest and etc. Since the operation is on minute, we need to convert the input to minute format first. Then we calculate the difference and try each operation to see how many times we could apply and update the difference after each operation.\n\n```cpp\nclass Solution {\npublic:\n int getMinutes(string t) {\n int res = 0;\n // handle HH\n res += (t[0] - \'0\') * 10;\n res += (t[1] - \'0\');\n res *= 60;\n // handle MM\n res += (t[3] - \'0\') * 10;\n res += (t[4] - \'0\');\n return res;\n }\n \n int convertTime(string current, string correct) {\n // convert inputs to minute format\n int from = getMinutes(current), to = getMinutes(correct);\n // init ans & calculate the difference\n int ans = 0, d = to - from;\n // available operators - use largest one first\n vector<int> ops{ 60, 15, 5, 1 };\n // try each operation - take as many as possible\n // and update the difference\n for (auto x : ops) ans += d / x, d %= x;\n return ans;\n }\n};\n```
1
0
['Greedy', 'C', 'C++']
0
minimum-number-of-operations-to-convert-time
Java: Difference in minutes
java-difference-in-minutes-by-dpksamir-2gfu
\npublic int convertTime(String current, String correct) {\n String[] currentTime = current.split(":");\n String[] correctTime = correct.split(":"
dpksamir
NORMAL
2022-07-18T14:05:37.355078+00:00
2022-07-18T14:05:37.355126+00:00
54
false
```\npublic int convertTime(String current, String correct) {\n String[] currentTime = current.split(":");\n String[] correctTime = correct.split(":");\n \n int correctMin = Integer.parseInt(correctTime[0]) * 60 + Integer.parseInt(correctTime[1]);\n int currentMin = Integer.parseInt(currentTime[0]) * 60 + Integer.parseInt(currentTime[1]);\n \n int diff = correctMin - currentMin;\n int steps = 0;\n while(diff>0)\n {\n if(diff>=60)\n {\n diff -=60;\n }\n else if(diff>=15)\n {\n diff -=15;\n }\n else if (diff>=5)\n {\n diff -=5;\n }\n else if(diff>=1)\n {\n diff -=1;\n }\n steps++;\n }\n\n return steps;\n }\n```
1
0
[]
1
minimum-number-of-operations-to-convert-time
rust
rust-by-kennylong-6wwb
rust\nimpl Solution {\n pub fn convert_time(current: String, correct: String) -> i32 {\n let current: Vec<_> = current.split(":").collect();\n
kennylong
NORMAL
2022-07-07T13:55:47.672576+00:00
2022-07-07T13:55:47.672628+00:00
24
false
```rust\nimpl Solution {\n pub fn convert_time(current: String, correct: String) -> i32 {\n let current: Vec<_> = current.split(":").collect();\n let correct: Vec<_> = correct.split(":").collect();\n let start0: i32 = current[0].parse().unwrap();\n let start1: i32 = current[1].parse().unwrap();\n let end0: i32 = correct[0].parse().unwrap();\n let end1: i32 = correct[1].parse().unwrap();\n\n let mut diff = (end0 - start0) * 60 + (end1 - start1);\n let mut cnt = 0;\n for n in vec![60, 15, 5, 1] {\n if diff >= n {\n cnt += diff / n;\n diff %= n\n }\n }\n cnt\n }\n}\n```
1
0
['Rust']
0
minimum-number-of-operations-to-convert-time
My 2ms Easy to understand JAVA code
my-2ms-easy-to-understand-java-code-by-p-3qi6
```\nclass Solution \n{\n public int convertTime(String current, String correct) \n {\n int cur_hou = Integer.parseInt(current.substring(0,2));\n
Pranjal_Dwivedi
NORMAL
2022-06-27T04:39:59.183392+00:00
2022-06-27T04:39:59.183446+00:00
59
false
```\nclass Solution \n{\n public int convertTime(String current, String correct) \n {\n int cur_hou = Integer.parseInt(current.substring(0,2));\n int cur_min = Integer.parseInt(current.substring(3,5));\n int cur = (cur_hou*60)+cur_min; //150\n \n int cor_hou = Integer.parseInt(correct.substring(0,2));\n int cor_min = Integer.parseInt(correct.substring(3,5));\n int cor = (cor_hou*60)+cor_min; //275\n \n int differ = cor-cur; //125\n int no_of_ops=0;\n \n while(differ!=0)\n {\n if(differ>=60)\n {\n differ=differ-60;\n no_of_ops++;\n }\n else if(differ>=15)\n {\n differ-=15;\n no_of_ops++;\n }\n else if(differ>=5)\n {\n differ-=5;\n no_of_ops++;\n }\n else\n {\n differ-=1;\n no_of_ops++;\n }\n }\n \n return no_of_ops;\n \n }\n}
1
0
['Java']
0
minimum-number-of-operations-to-convert-time
Why greedy works here?
why-greedy-works-here-by-r_fadeup-5hyf
I know there is papaer regarding cannonical sequence of numbers which can identify if a problem like this can be solved using Greedy way. https://arxiv.org/pdf/
r_fadeup
NORMAL
2022-05-02T20:56:58.592736+00:00
2022-05-02T20:56:58.592779+00:00
39
false
I know there is papaer regarding cannonical sequence of numbers which can identify if a problem like this can be solved using Greedy way. https://arxiv.org/pdf/0809.0400.pdf\nIs there any simple way to decide if we can use greedy way to solve this kind problem.
1
0
[]
0
minimum-number-of-operations-to-convert-time
Simple Python Solution with Detailed Explanation (faster than 99%, easy to understand)
simple-python-solution-with-detailed-exp-sulf
\n\nclass Solution:\n def convertTime(self, current: str, correct: str) -> int:\n \n newcu = current.split(\':\') # extract hours and minu
wulalawulalawu
NORMAL
2022-04-24T05:41:50.921983+00:00
2022-04-24T05:41:50.922033+00:00
60
false
```\n\n```class Solution:\n def convertTime(self, current: str, correct: str) -> int:\n \n newcu = current.split(\':\') # extract hours and minutes from current and correct\n newco = correct.split(\':\')\n \n newcu = [int(x) for x in newcu] # change string to integer\n newco = [int(x) for x in newco]\n \n newcu1 = newcu[0]*60 + newcu[1] # change hours to minutes\n newco1 = newco[0]*60 + newco[1]\n \n diff = newco1 - newcu1 # get the difference between correct and current in minutes\n \n nums = diff//60 + diff%60//15 + diff%60%15//5 + diff%60%15%5 # divide by 60, then + remainder divide by 15, then + remainder divide by 5 then + remainder of 5\n\n return nums
1
0
[]
0
minimum-number-of-operations-to-convert-time
Java
java-by-n0face-otnz
\nclass Solution {\n public int convertTime(String current, String correct) {\n int curr=Integer.parseInt(current.substring(0,2))*60;\n curr+=
n0face
NORMAL
2022-04-23T07:49:02.936947+00:00
2022-04-23T07:49:02.936991+00:00
68
false
```\nclass Solution {\n public int convertTime(String current, String correct) {\n int curr=Integer.parseInt(current.substring(0,2))*60;\n curr+=Integer.parseInt(current.substring(3,5));\n \n int corr=Integer.parseInt(correct.substring(0,2))*60;\n corr+=Integer.parseInt(correct.substring(3,5));\n\n corr=corr-curr;\n \n int res=0;\n res+=corr/60;\n corr=corr%60;\n \n res+=corr/15;\n corr=corr%15;\n \n res+=corr/5;\n corr=corr%5;\n \n res+=corr/1;\n \n\n return res;\n\n \n \n \n \n \n \n \n }\n}\n```
1
0
[]
0
minimum-number-of-operations-to-convert-time
[Python3] division & modulo
python3-division-modulo-by-ye15-ztgk
Please pull this commit for solutions of weekly 287.\n\n\nclass Solution:\n def convertTime(self, current: str, correct: str) -> int:\n fn = lambda x,
ye15
NORMAL
2022-04-18T18:41:02.107895+00:00
2022-04-18T19:10:44.587658+00:00
90
false
Please pull this [commit](https://github.com/gaosanyong/leetcode/commit/f2b4a5c0268eb27201b136764bb0b6ad3880c6f6) for solutions of weekly 287.\n\n```\nclass Solution:\n def convertTime(self, current: str, correct: str) -> int:\n fn = lambda x, y: 60*x + y\n m0 = fn(*map(int, current.split(\':\')))\n m1 = fn(*map(int, correct.split(\':\')))\n ans = 0 \n diff = m1 - m0 \n for x in 60, 15, 5, 1: \n ans += diff // x\n diff %= x\n return ans \n```
1
0
['Python3']
0
minimum-number-of-operations-to-convert-time
Python (Coin change problem)
python-coin-change-problem-by-rnotappl-3838
\n def convertTime(self, current, correct):\n current = int(current.split(":")[0])60 + int(current.split(":")[1])\n correct = int(correct.split
rnotappl
NORMAL
2022-04-17T14:42:26.554032+00:00
2022-04-17T14:42:26.554069+00:00
29
false
\n def convertTime(self, current, correct):\n current = int(current.split(":")[0])*60 + int(current.split(":")[1])\n correct = int(correct.split(":")[0])*60 + int(correct.split(":")[1])\n \n amount, coins = correct - current, [1,5,15,60]\n \n dp = [float("inf")]*(amount+1)\n \n dp[0] = 0\n \n for coin in coins:\n for i in range(coin, amount+1):\n dp[i] = min(dp[i], 1 + dp[i-coin])\n \n return dp[-1]
1
0
[]
0