|
| 1 | +✅ LeetCode 2138 – Divide a String Into Groups of Size k |
| 2 | + |
| 3 | +class Solution { |
| 4 | + public String[] divideString(String s, int k, char fill) { |
| 5 | + int n = s.length(); |
| 6 | + int size = (n + k - 1) / k; // ceiling of n/k |
| 7 | + String[] result = new String[size]; |
| 8 | + |
| 9 | + int index = 0; |
| 10 | + for (int i = 0; i < n; i += k) { |
| 11 | + StringBuilder sb = new StringBuilder(); |
| 12 | + for (int j = i; j < i + k; j++) { |
| 13 | + if (j < n) sb.append(s.charAt(j)); |
| 14 | + else sb.append(fill); |
| 15 | + } |
| 16 | + result[index++] = sb.toString(); |
| 17 | + } |
| 18 | + |
| 19 | + return result; |
| 20 | + } |
| 21 | +} |
| 22 | + |
| 23 | +Explanation |
| 24 | + |
| 25 | +public String[] divideString(String s, int k, char fill) |
| 26 | +🔹 Hume string s ko k-k characters ke group mein divide karna hai. |
| 27 | +🔹 Agar last group chhota ho toh fill character se pad karna hai. |
| 28 | + |
| 29 | +int n = s.length(); |
| 30 | +🔹 Total length of string. |
| 31 | + |
| 32 | +int size = (n + k - 1) / k; |
| 33 | +🔹 Groups ka total count calculate kiya using ceiling formula. |
| 34 | + |
| 35 | +String[] result = new String[size]; |
| 36 | +🔹 Final result array banaya jisme hum groups store karenge. |
| 37 | + |
| 38 | +int index = 0; |
| 39 | +🔹 Group insert karne ke liye index tracker. |
| 40 | + |
| 41 | +for (int i = 0; i < n; i += k) |
| 42 | +🔹 Loop har k characters pe chalta hai. |
| 43 | + |
| 44 | +StringBuilder sb = new StringBuilder(); |
| 45 | +🔹 Group banane ke liye temporary StringBuilder use kiya. |
| 46 | + |
| 47 | +for (int j = i; j < i + k; j++) |
| 48 | +🔹 k size ka group banane ke liye inner loop. |
| 49 | + |
| 50 | +if (j < n) sb.append(s.charAt(j)); |
| 51 | +🔹 Agar string ka character available hai toh use add karo. |
| 52 | + |
| 53 | +else sb.append(fill); |
| 54 | +🔹 Nahi toh fill character daal do. |
| 55 | + |
| 56 | +result[index++] = sb.toString(); |
| 57 | +🔹 Group complete hone ke baad array mein store karo. |
| 58 | + |
| 59 | +return result; |
| 60 | +🔹 Saare groups return kar do. |
| 61 | +🧠 Example: |
| 62 | +Input: s = "abcdefghi", k = 3, fill = 'x' |
| 63 | + |
| 64 | +Groups: |
| 65 | +["abc", "def", "ghi"] |
| 66 | + |
| 67 | +Input: s = "abcdefghij", k = 3, fill = 'z' |
| 68 | +→ ["abc", "def", "ghz"] |
| 69 | + |
| 70 | +Time and Space Complexity: |
| 71 | +Item Complexity |
| 72 | +Time O(n) |
| 73 | +Space O(n) |
| 74 | + |
| 75 | +🔗 Need more help or Java tricks? |
| 76 | +https://www.linkedin.com/in/saurabh884095/ |
0 commit comments