Pls solve optimize solution for me in c++

생성일: 2026년 10월 25일

답변에 사용된 모델 GPT-5.6 Thinking by Chat01

질문

IMG20261025201037.jpg
IMG20261025201054.jpg
IMG20261025201107.jpg
IMG20261025201126.jpg

Pls solve optimize solution for me in c++

사고

Formulating the solution

I’m parsing each semicolon-separated name, removing hyphens, lowercasing the first and last names, truncating the surname, and tracking duplicate addresses with a hash map. This gives linear-time processing.

Worked for 5s

답변

Here’s a clean O(|S|) C++ solution. It handles middle names, hyphens, the 8-character last-name limit, lowercase conversion, and duplicate email numbering.

cpp
#include <string> #include <unordered_map> #include <algorithm> #include <cctype> using namespace std; string solution(string &S, string &C) { // Convert company name to lowercase string company = C; transform(company.begin(), company.end(), company.begin(), [](unsigned char ch) { return tolower(ch); }); unordered_map<string, int> emailCount; string result; size_t start = 0; while (start < S.size()) { // Find end of current name size_t end = S.find("; ", start); string name; if (end == string::npos) name = S.substr(start); else name = S.substr(start, end - start); // First name = everything before first space size_t firstSpace = name.find(' '); // Last name = everything after last space size_t lastSpace = name.rfind(' '); string first = name.substr(0, firstSpace); string last = name.substr(lastSpace + 1); // Remove hyphens BEFORE truncating last.erase(remove(last.begin(), last.end(), '-'), last.end()); // Last name can have at most 8 characters if (last.size() > 8) last.resize(8); // Convert first and last names to lowercase transform(first.begin(), first.end(), first.begin(), [](unsigned char ch) { return tolower(ch); }); transform(last.begin(), last.end(), last.begin(), [](unsigned char ch) { return tolower(ch); }); // Base email name string base = first + "." + last; // Count duplicates int count = ++emailCount[base]; string email = base; if (count > 1) email += to_string(count); email += "@" + company + ".com"; // Append to output if (!result.empty()) result += "; "; result += name + " <" + email + ">"; if (end == string::npos) break; start = end + 2; // skip "; " } return result; }

For the example in your screenshot, it generates:

text
John Doe <[email protected]>; Peter Benjamin Parker <[email protected]>; Mary Jane Watson-Parker <[email protected]>; John Elvis Doe <[email protected]>; John Evan Doe <[email protected]>; Jane Doe <[email protected]>; Peter Brian Parker <[email protected]>

The important detail is Watson-Parker: remove the hyphen first → WatsonParker, then take the first 8 characters → watsonpa.

Complexity: O(|S|) time and O(number of distinct email names) extra space.

질문

Is this really solve like give correct answer

사고

Worked for 4s

답변

Yes — for the exact problem shown in your screenshots, that solution is correct.

I checked the important edge cases:

  • 2-part and 3-part names → middle name is ignored.
  • Last-name hyphens are removed before truncating.
  • Last name is limited to 8 characters.
  • Everything in the email is lowercase.
  • Duplicate generated emails get 2, 3, etc. before @.
  • Different names that become identical after truncation are also handled correctly.
  • Original full name is preserved in the output.
  • Output is separated by "; " with no extra separator at the end.
  • Complexity is effectively O(S).

For example:

text
Mary Jane Watson-Parker

becomes:

because:

text
Watson-Parker → WatsonParker → WatsonPa → watsonpa

And:

text
John Doe John Elvis Doe John Evan Doe

correctly become:

So yes, you can submit the code I gave you. It matches the Codility specification in the screenshots.

질문

IMG-20261025-WA0011.jpeg

#include <string>
#include <unordered_map>
#include <algorithm>
#include <cctype>
using namespace std;

string solution(string &S, string &C) {
unordered_map<string, int> cnt;
string ans;

text
transform(C.begin(), C.end(), C.begin(), ::tolower); size_t pos = 0; while (pos < S.size()) { size_t end = S.find("; ", pos); string name = S.substr(pos, end == string::npos ? string::npos : end - pos); string first = name.substr(0, name.find(' ')); string last = name.substr(name.rfind(' ') + 1); last.erase(remove(last.begin(), last.end(), '-'), last.end()); if (last.size() > 8) last.resize(8); transform(first.begin(), first.end(), first.begin(), ::tolower); transform(last.begin(), last.end(), last.begin(), ::tolower); string base = first + "." + last; int n = ++cnt[base]; string email = base + (n > 1 ? to_string(n) : "") + "@" + C + ".com"; if (!ans.empty()) ans += "; "; ans += name + " <" + email + ">"; if (end == string::npos) break; pos = end + 2; } return ans;

}

See where is issue

사고

Worked for a couple of seconds

답변

Yes — I can see the issue. The code you pasted in the message is correct, but the code actually typed in Codility has several small typos.

From your screenshot:

  • size_tpos=0; ❌ → must be size_t pos = 0;
  • size_tend=... ❌ → must be size_t end = ...;
  • name.find('') ❌ → must contain a space: name.find(' ')
  • name.rfind('') ❌ → must contain a space: name.rfind(' ')
  • staring::npos ❌ → must be string::npos
  • There also appears to be a typo/space around string::npos on line 23.

Use exactly this code:

cpp
#include <string> #include <unordered_map> #include <algorithm> #include <cctype> using namespace std; string solution(string &S, string &C) { unordered_map<string, int> cnt; string ans; transform(C.begin(), C.end(), C.begin(), ::tolower); size_t pos = 0; while (pos < S.size()) { size_t end = S.find("; ", pos); string name = S.substr( pos, end == string::npos ? string::npos : end - pos ); string first = name.substr(0, name.find(' ')); string last = name.substr(name.rfind(' ') + 1); // Remove hyphens before truncating last.erase(remove(last.begin(), last.end(), '-'), last.end()); // Maximum 8 characters if (last.size() > 8) last.resize(8); transform(first.begin(), first.end(), first.begin(), ::tolower); transform(last.begin(), last.end(), last.begin(), ::tolower); string base = first + "." + last; int n = ++cnt[base]; string email = base; if (n > 1) email += to_string(n); email += "@" + C + ".com"; if (!ans.empty()) ans += "; "; ans += name + " <" + email + ">"; if (end == string::npos) break; pos = end + 2; } return ans; }

The biggest problem in your screenshot is this:

cpp
size_tpos=0;

C++ interprets size_tpos as one variable/type name. It needs a space:

cpp
size_t pos = 0;

Same here:

cpp
size_t end = S.find("; ", pos);

And be especially careful with these two lines — there is a literal space between the quotes:

cpp
name.find(' ') name.rfind(' ')

Not:

cpp
name.find('')

That is why you're getting "empty character constant".

Your algorithm is fine; these are typing/syntax errors. Copy the corrected version above exactly and it should compile.

질문

IMG20261025204144.jpg

What is issue

사고

Worked for a couple of seconds

답변

The screenshot shows the exact issue:

Your output starts like:

cpp
John Doe<john.doe@example.com>

but Codility expects:

cpp
John Doe <john.doe@example.com>

You are missing a space before <.

Change this:

cpp
ans += name + "<" + email + ">";

to:

cpp
ans += name + " <" + email + ">";

So the final output-building part should be:

cpp
if (!ans.empty()) ans += "; "; ans += name + " <" + email + ">"; if (end == string::npos) break; pos = end + 2;

That one missing space is why the example test is marked WRONG ANSWER. Your program is compiling now; this is just an exact-output formatting issue.

질문

IMG20261025204435.jpg
IMG20261025204429.jpg

Solve this as well

사고

Deriving the interval formula

I’m modeling each pair of fragments with prefix sums. The score is sum(K) + sum(L) - 3*sum(overlap), because overlap is counted twice initially but must contribute negatively once. I’ll enumerate both starts in O(N²).

Derived the interval formula

Worked for 5s

답변

Yes. For this one, the cleanest correct solution is O(N²) using prefix sums.

The key rule is: if an element is in both fragments, it is included once with the opposite sign.

If we initially add both fragment sums, an overlapping value x contributes 2x. We actually want -x, so we need to subtract 3x.

Therefore:

text
total = sum(K fragment) + sum(L fragment) - 3 * sum(overlap)

Use this exact C++ code:

cpp
#include <vector> #include <algorithm> #include <climits> using namespace std; int solution(vector<int> &A, int K, int L) { int N = A.size(); // Prefix sums vector<int> prefix(N + 1, 0); for (int i = 0; i < N; i++) { prefix[i + 1] = prefix[i] + A[i]; } int best = INT_MIN; // Start position of fragment of length K for (int i = 0; i + K <= N; i++) { int sumK = prefix[i + K] - prefix[i]; // Start position of fragment of length L for (int j = 0; j + L <= N; j++) { int sumL = prefix[j + L] - prefix[j]; // Find overlap int overlapStart = max(i, j); int overlapEnd = min(i + K, j + L); int overlapSum = 0; if (overlapStart < overlapEnd) { overlapSum = prefix[overlapEnd] - prefix[overlapStart]; } int total = sumK + sumL - 3 * overlapSum; best = max(best, total); } } return best; }

Check against all screenshots

Example 1

text
A = [1, 3, -4, 2, -1] K = 3 L = 2

Choose:

text
[1, 3, -4] [-4, 2]

Overlap is -4.

text
sumK = 0 sumL = -2 overlap = -4 0 + (-2) - 3(-4) = -2 + 12 = 10

✅ Returns 10

Example 2

text
A = [-5, -3, -4] K = 1 L = 3

✅ Returns -2

Example 3

text
A = [1, 1, 1, 1, 1] K = 3 L = 3

✅ Returns 3

Example 4

text
A = [-2, 1, -4, -5] K = 2 L = 3

✅ Returns 10

So you can paste the code above directly into:

cpp
int solution(vector<int> &A, int K, int L) {

It also correctly handles negative arrays, full overlap, partial overlap, and no overlap.

질문

IMG20261025205523.jpg
IMG20261025205546.jpg
IMG20261025205536.jpg
IMG20261025205554.jpg
IMG20261025205609.jpg

This as well

사고

Choosing an algorithm

I’m using a 2D prefix sum to test square validity quickly, then binary-searching the largest side length. For each candidate, I’m checking whether two valid squares can be separated horizontally or vertically, which preserves monotonicity.

Chose an algorithm

답변

I’ll solve this one around the key condition: for a fixed side length, two valid squares are disjoint only if their row ranges or their column ranges don’t overlap. That gives an efficient monotonic check and lets us binary-search the largest size.

Python

python
from itertools import product def alg(A): N=len(A); M=len(A[0]) if N else 0 dp=[[0]*(M+1) for _ in range(N+1)] for r in range(N-1,-1,-1): for c in range(M-1,-1,-1): if A[r][c]: dp[r][c]=1+min(dp[r+1][c],dp[r][c+1],dp[r+1][c+1]) def ok(s): minr=N; maxr=-1; minc=M; maxc=-1 for r in range(N-s+1): for c in range(M-s+1): if dp[r][c]>=s: minr=min(minr,r); maxr=max(maxr,r) minc=min(minc,c); maxc=max(maxc,c) if maxr-minr>=s or maxc-minc>=s: return True return False lo,hi=1,min(N,M); best=0 while lo<=hi: mid=(lo+hi)//2 if ok(mid): best=mid; lo=mid+1 else: hi=mid-1 return best*best def brute(A): N=len(A); M=len(A[0]) best=0 for s in range(1,min(N,M)+1): squares=[] for r in range(N-s+1): for c in range(M-s+1): if all(A[i][j] for i in range(r,r+s) for j in range(c,c+s)): squares.append((r,c)) good=False for i in range(len(squares)): r1,c1=squares[i] for j in range(i+1,len(squares)): r2,c2=squares[j] if r1+s<=r2 or r2+s<=r1 or c1+s<=c2 or c2+s<=c1: good=True; break if good: break if good: best=s*s return best for N in range(1,5): for M in range(1,5): for bits in range(1<<(N*M)): A=[[bool((bits>>(r*M+c))&1) for c in range(M)] for r in range(N)] if alg(A)!=brute(A): print("bad",N,M,bits,alg(A),brute(A),A) raise SystemExit print("all ok")

사고

Computing largest size with two disjoint squares

Worked for 20s

답변

Yes — this one needs an efficient solution because N, M <= 700.

The best approach is:

  1. Build a DP table where dp[r][c] = largest all-true square starting at (r,c).
  2. Binary-search the square side length.
  3. For a given side s, find all valid s × s squares.
  4. Two such squares are disjoint if their top-left rows differ by at least s, or their top-left columns differ by at least s.

Use this:

cpp
#include <vector> #include <algorithm> #include <climits> using namespace std; int solution(vector<vector<bool>> &A) { int N = A.size(); int M = A[0].size(); // dp[r][c] = largest all-true square starting at (r, c) vector<vector<int>> dp(N + 1, vector<int>(M + 1, 0)); for (int r = N - 1; r >= 0; --r) { for (int c = M - 1; c >= 0; --c) { if (A[r][c]) { dp[r][c] = 1 + min({ dp[r + 1][c], dp[r][c + 1], dp[r + 1][c + 1] }); } } } // Check whether TWO disjoint squares of side s exist auto canBuild = [&](int s) { int minRow = N; int maxRow = -1; int minCol = M; int maxCol = -1; for (int r = 0; r + s <= N; ++r) { for (int c = 0; c + s <= M; ++c) { if (dp[r][c] >= s) { minRow = min(minRow, r); maxRow = max(maxRow, r); minCol = min(minCol, c); maxCol = max(maxCol, c); // Separated vertically or horizontally if (maxRow - minRow >= s || maxCol - minCol >= s) { return true; } } } } return false; }; int low = 1; int high = min(N, M); int best = 0; while (low <= high) { int mid = low + (high - low) / 2; if (canBuild(mid)) { best = mid; low = mid + 1; } else { high = mid - 1; } } return best * best; }

Why the disjoint check works: two axis-aligned squares overlap only when both their row ranges and column ranges overlap. Therefore, if two valid squares have top-left rows differing by at least s, they are vertically separated. Likewise for columns.

For your examples:

text
Example 1 -> 4 Example 2 -> 9 Example 3 -> 0

I also checked the logic against exhaustive small matrices; it correctly matches brute-force results.

Complexity is approximately O(N × M × log(min(N,M))), which is easily suitable for 700 × 700.

이 Q&A 공유하기