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
print-in-order
Using Conditional Variables and lock :: std:: C++ Easy sol
using-conditional-variables-and-lock-std-7q79
\n\n# Code\n\nclass Foo {\n std:: mutex m;\n std:: condition_variable cv;\n int turn;\npublic:\n Foo() {\n turn= 0;\n }\n\n void first(
ankush20386
NORMAL
2024-03-16T06:01:17.812087+00:00
2024-03-16T06:01:17.812111+00:00
1,124
false
\n\n# Code\n```\nclass Foo {\n std:: mutex m;\n std:: condition_variable cv;\n int turn;\npublic:\n Foo() {\n turn= 0;\n }\n\n void first(function<void()> printFirst) {\n \n // printFirst() outputs "first". Do not change or remove this line.\n printFirst();\n turn=1;\n cv.notify_all();\n }\n\n void second(function<void()> printSecond) {\n std:unique_lock<std::mutex>lock(m);\n while(turn!=1){\n cv.wait(lock);\n }\n // printSecond() outputs "second". Do not change or remove this line.\n printSecond();\n turn=2;\n cv.notify_all();\n\n }\n\n void third(function<void()> printThird) {\n std:unique_lock<std::mutex>lock(m);\n while(turn!=2){\n cv.wait(lock);\n }\n // printThird() outputs "third". Do not change or remove this line.\n printThird();\n\n }\n};\n```
3
0
['C++']
2
print-in-order
Semaphore solution
semaphore-solution-by-oskardp-ivbd
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
OskarDP
NORMAL
2023-09-21T10:09:23.316207+00:00
2023-09-21T10:09:23.316234+00:00
507
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```\nusing System.Threading;\n\npublic class Foo {\n\n private static Semaphore s1;\n private static Semaphore s2;\n\n public Foo() {\n s1 = new Semaphore(initialCount: 0, maximumCount: 1);\n s2 = new Semaphore(initialCount: 0, maximumCount: 1);\n }\n\n public void First(Action printFirst) {\n \n printFirst();\n s1.Release();\n }\n\n public void Second(Action printSecond) {\n \n s1.WaitOne();\n printSecond();\n s2.Release();\n }\n\n public void Third(Action printThird) {\n s2.WaitOne();\n printThird();\n }\n}\n```
3
0
['C#']
1
print-in-order
C# | Faster than 100% (90ms) | TaskCompletionSource | Rightest Solution 🟢
c-faster-than-100-90ms-taskcompletionsou-qiq9
Code\n\nusing System.Threading.Tasks;\npublic class Foo {\n private TaskCompletionSource _f;\n private TaskCompletionSource _s;\n \n public Foo()\n
Encapsulating
NORMAL
2023-07-31T08:56:01.852615+00:00
2023-07-31T08:56:01.852632+00:00
424
false
# Code\n```\nusing System.Threading.Tasks;\npublic class Foo {\n private TaskCompletionSource _f;\n private TaskCompletionSource _s;\n \n public Foo()\n {\n _f = new TaskCompletionSource();\n _s = new TaskCompletionSource();\n }\n\n public void First(Action printFirst) {\n printFirst();\n _f.SetResult();\n }\n\n public void Second(Action printSecond)\n {\n _f.Task.Wait();\n printSecond();\n _s.SetResult();\n }\n\n public void Third(Action printThird)\n { \n _s.Task.Wait();\n printThird();\n }\n}\n```
3
0
['C#']
0
print-in-order
[C++]Simple solution using mutex.
csimple-solution-using-mutex-by-bigbigbi-f5ts
I am a newbie about concurrency. Is this right way?\n\n# Code\n\n\n\nclass Foo {\nprivate:\n mutex task1, task2;\npublic:\n Foo() {\n task1.lock();
bigbigbige
NORMAL
2023-02-26T05:28:40.708280+00:00
2023-02-26T05:32:09.186152+00:00
1,083
false
I am a newbie about concurrency. Is this right way?\n\n# Code\n```\n\n\nclass Foo {\nprivate:\n mutex task1, task2;\npublic:\n Foo() {\n task1.lock();\n task2.lock();\n }\n\n void first(function<void()> printFirst) {\n \n // printFirst() outputs "first". Do not change or remove this line.\n printFirst();\n\n task1.unlock();\n }\n\n void second(function<void()> printSecond) {\n task1.lock();\n\n // printSecond() outputs "second". Do not change or remove this line.\n printSecond();\n\n task2.unlock();\n }\n\n void third(function<void()> printThird) {\n task2.lock();\n\n // printThird() outputs "third". Do not change or remove this line.\n printThird();\n }\n};\n```
3
0
['C++']
1
print-in-order
JAVA solution using Semaphore
java-solution-using-semaphore-by-samiksh-q33s
Complexity\n- Time complexity:\nO(1)\n\n- Space complexity:\nO(1)\n\n# Code\n\nclass Foo {\n\n Semaphore first;\n Semaphore second;\n Semaphore third;\
samiksha12
NORMAL
2022-11-17T06:35:08.017648+00:00
2022-11-17T06:35:17.933818+00:00
1,171
false
# Complexity\n- Time complexity:\nO(1)\n\n- Space complexity:\nO(1)\n\n# Code\n```\nclass Foo {\n\n Semaphore first;\n Semaphore second;\n Semaphore third;\n public Foo() {\n first = new Semaphore(1);\n second = new Semaphore(0);\n third = new Semaphore(0);\n }\n\n public void first(Runnable printFirst) throws InterruptedException {\n first.acquire();\n // printFirst.run() outputs "first". Do not change or remove this line.\n printFirst.run();\n second.release();\n }\n\n public void second(Runnable printSecond) throws InterruptedException {\n second.acquire();\n // printSecond.run() outputs "second". Do not change or remove this line.\n printSecond.run();\n third.release();\n }\n\n public void third(Runnable printThird) throws InterruptedException {\n third.acquire();\n // printThird.run() outputs "third". Do not change or remove this line.\n printThird.run();\n first.release();\n }\n}\n```
3
0
['Java']
0
print-in-order
Java Phaser
java-phaser-by-arodin-35jm
Code\n\nclass Foo {\n private Phaser phaser = new Phaser(3);\n\n public Foo() { }\n\n public void first(Runnable printFirst) throws InterruptedExceptio
arodin
NORMAL
2022-11-08T02:20:46.630686+00:00
2022-11-08T02:20:46.630721+00:00
443
false
# Code\n```\nclass Foo {\n private Phaser phaser = new Phaser(3);\n\n public Foo() { }\n\n public void first(Runnable printFirst) throws InterruptedException {\n // printFirst.run() outputs "first". Do not change or remove this line.\n printFirst.run();\n phaser.arriveAndDeregister();\n }\n\n public void second(Runnable printSecond) throws InterruptedException {\n while (phaser.getPhase() != 1) {\n phaser.arriveAndAwaitAdvance();\n }\n // printSecond.run() outputs "second". Do not change or remove this line.\n printSecond.run();\n phaser.arriveAndDeregister();\n }\n\n public void third(Runnable printThird) throws InterruptedException {\n while (phaser.getPhase() != 2) {\n phaser.arriveAndAwaitAdvance();\n }\n // printThird.run() outputs "third". Do not change or remove this line.\n printThird.run();\n }\n}\n```
3
0
['Java']
1
print-in-order
[C#] blocking threads with AutoResetEvent primitives
c-blocking-threads-with-autoresetevent-p-vcwi
Intuition\nFirst thing that came to my mind was to block second, then third method until prefious will be completed\n\n# Approach\nI decided to block set blocke
poltaratskiy
NORMAL
2022-10-29T13:34:08.129564+00:00
2022-10-29T13:34:08.129607+00:00
803
false
# Intuition\nFirst thing that came to my mind was to block second, then third method until prefious will be completed\n\n# Approach\nI decided to block set blockers in second and third methods. We create 2 blockers in nonsignal state, that means the method WaitOne() will block threads. \n\nMethod First() without blockers, after running printFirst() we transfer _secondBlocker in signal state by running method Set(), so _secondBlocker unblocks blocked threads. The same with method Third()\n\n# Code\n```\nusing System.Threading;\n\npublic class Foo {\n private readonly AutoResetEvent _secondBlocker = new AutoResetEvent(false);\n private readonly AutoResetEvent _thirdBlocker = new AutoResetEvent(false);\n\n public Foo() {\n \n }\n\n public void First(Action printFirst) {\n printFirst();\n _secondBlocker.Set();\n }\n\n public void Second(Action printSecond) {\n _secondBlocker.WaitOne();\n printSecond();\n _thirdBlocker.Set();\n }\n\n public void Third(Action printThird) {\n _thirdBlocker.WaitOne();\n printThird();\n }\n}\n```
3
0
['C#']
0
print-in-order
Java Real Simple Solution
java-real-simple-solution-by-ahead4-f8h2
\nclass Foo {\n private volatile int num = 1;\n public Foo() {\n\n }\n\n public void first(Runnable printFirst) throws InterruptedException {\n
ahead4
NORMAL
2022-09-05T07:09:31.539817+00:00
2022-09-07T07:57:37.842225+00:00
1,288
false
```\nclass Foo {\n private volatile int num = 1;\n public Foo() {\n\n }\n\n public void first(Runnable printFirst) throws InterruptedException {\n while(num != 1){\n }\n\n // printFirst.run() outputs "first". Do not change or remove this line.\n printFirst.run();\n num++;\n }\n\n public void second(Runnable printSecond) throws InterruptedException {\n while(num != 2){\n }\n // printSecond.run() outputs "second". Do not change or remove this line.\n printSecond.run();\n num++;\n }\n\n public void third(Runnable printThird) throws InterruptedException {\n while(num != 3){\n }\n // printThird.run() outputs "third". Do not change or remove this line.\n printThird.run();\n num++;\n }\n}\n```
3
0
['Java']
0
print-in-order
Semaphore Solution | Simple Java code
semaphore-solution-simple-java-code-by-i-apfl
\nclass Foo {\n\n private Semaphore forTwo;\n private Semaphore forThree;\n \n public Foo() {\n forTwo = new Semaphore(0);\n forThree
ishan_aggarwal
NORMAL
2022-08-20T17:09:33.865763+00:00
2022-08-20T17:09:33.865804+00:00
281
false
```\nclass Foo {\n\n private Semaphore forTwo;\n private Semaphore forThree;\n \n public Foo() {\n forTwo = new Semaphore(0);\n forThree = new Semaphore(0);\n }\n\n\n \n public void first(Runnable printFirst) throws InterruptedException {\n \n // printFirst.run() outputs "first". Do not change or remove this line.\n printFirst.run();\n forTwo.release();\n }\n\n public void second(Runnable printSecond) throws InterruptedException {\n \n forTwo.acquire();\n \n // printSecond.run() outputs "second". Do not change or remove this line.\n printSecond.run();\n \n forThree.release();\n }\n\n public void third(Runnable printThird) throws InterruptedException {\n \n \n forThree.acquire();\n \n // printThird.run() outputs "third". Do not change or remove this line.\n printThird.run();\n }\n}\n```
3
0
[]
1
print-in-order
Brainless solution using time.sleep
brainless-solution-using-timesleep-by-us-v4he
Here is my simplest and brainless solution using time.sleep. Why and How did I think of it? People use this approach in automation where I work.\n\nPython3\nfro
useraccessdenied
NORMAL
2022-05-06T11:05:33.298079+00:00
2022-05-06T11:05:33.298105+00:00
509
false
Here is my simplest and brainless solution using time.sleep. Why and How did I think of it? People use this approach in automation where I work.\n\n```Python3\nfrom time import sleep\n\nclass Foo:\n def __init__(self):\n pass\n\n\n def first(self, printFirst: \'Callable[[], None]\') -> None:\n \n # printFirst() outputs "first". Do not change or remove this line.\n printFirst()\n\n\n def second(self, printSecond: \'Callable[[], None]\') -> None:\n sleep(0.05)\n # printSecond() outputs "second". Do not change or remove this line.\n printSecond()\n\n\n def third(self, printThird: \'Callable[[], None]\') -> None:\n sleep(0.1)\n # printThird() outputs "third". Do not change or remove this line.\n printThird()\n```
3
0
['Python']
1
print-in-order
2-Lines Python Solution || 75% Faster || Memory less than 95%
2-lines-python-solution-75-faster-memory-ln4i
\nclass Foo:\n is_first_executed=False\n is_second_executed=False\n def __init__(self):\n pass\n\n def first(self, printFirst):\n prin
Taha-C
NORMAL
2022-03-16T23:35:19.274428+00:00
2022-03-16T23:35:19.274453+00:00
943
false
```\nclass Foo:\n is_first_executed=False\n is_second_executed=False\n def __init__(self):\n pass\n\n def first(self, printFirst):\n printFirst()\n self.is_first_executed=True\n\n def second(self, printSecond):\n while not self.is_first_executed: continue \n printSecond()\n self.is_second_executed=True\n \n def third(self, printThird):\n while not self.is_second_executed: continue\n printThird()\n```\n\n-----------------\n### ***Another Solution***\n```\nfrom threading import Event\nclass Foo:\n def __init__(self):\n self.event1=Event()\n self.event2=Event()\n\n def first(self, printFirst: \'Callable[[], None]\') -> None:\n printFirst()\n self.event1.set()\n\n def second(self, printSecond: \'Callable[[], None]\') -> None:\n self.event1.wait()\n printSecond()\n self.event2.set()\n\n def third(self, printThird: \'Callable[[], None]\') -> None:\n self.event2.wait()\n printThird()\n```\n-------------------\n***----- Taha Choura -----***\n*taha.choura@outlook.com*
3
0
['Python', 'Python3']
1
print-in-order
C++ | zero semaphore with comments
c-zero-semaphore-with-comments-by-spyole-ysxz
\n#include<semaphore.h>\nclass Foo {\npublic:\n sem_t sem1;\n sem_t sem2;\n Foo() {\n sem_init(&sem1,0,0);\n sem_init(&sem2,0,0);\n
spyole97
NORMAL
2022-01-25T20:55:34.225264+00:00
2022-01-25T21:00:17.139972+00:00
362
false
```\n#include<semaphore.h>\nclass Foo {\npublic:\n sem_t sem1;\n sem_t sem2;\n Foo() {\n sem_init(&sem1,0,0);\n sem_init(&sem2,0,0);\n \n }\n\n void first(function<void()> printFirst) {\n \n printFirst();\n sem_post(&sem1);// increased the value to 1 so now two can be executed\n }\n\n void second(function<void()> printSecond) {\n \n sem_wait(&sem1);//see if the value of the semaphore is > 0 or not if it is then one already was printed\n printSecond();\n sem_post(&sem2);// printed two so now increased the value of the semaphore sem2\n }\n\n void third(function<void()> printThird) {\n \n sem_wait(&sem2);// if the value of the sem2 > 0 them two was already printed \n printThird();\n }\n};\n```
3
0
[]
0
print-in-order
Explanation of the solution in Java
explanation-of-the-solution-in-java-by-i-hzrp
You can use a countdownlatch, semaphore, regular mutex or lock object. I noticed a solution that relied upon volatile only but that is not right. A solution wit
idmrealm
NORMAL
2021-10-30T02:58:43.066685+00:00
2021-10-30T02:58:43.066726+00:00
262
false
You can use a countdownlatch, semaphore, regular mutex or lock object. I noticed a solution that relied upon volatile only but that is not right. A solution without wait/notify will cause CPU churns and spinning so you must introduce that if you are serious about MT safe programming. If you choose to go with CountDownLatch or Semaphores, you can create 2 indepent ones and there is an ordering one after another. I chose to use a lock object to demonstrate in detail how we enforce the ordering. Note that you must have a while loop to protect against the spurious wakeups. \n\n```\nimport java.util.concurrent.*;\n\nclass Foo {\n private final Lock lock = new ReentrantLock();\n private final Condition secondThread = lock.newCondition();\n private final Condition thirdThread = lock.newCondition();\n private int step = 1;\n \n public Foo() {\n \n }\n\n public void first(Runnable printFirst) throws InterruptedException {\n lock.lock(); \n try {\n // printFirst.run() outputs "first". Do not change or remove this line.\n printFirst.run();\n // signal 2nd.\n step = 2;\n secondThread.signal();\n } finally {\n lock.unlock();\n }\n }\n\n public void second(Runnable printSecond) throws InterruptedException {\n \n // printSecond.run() outputs "second". Do not change or remove this line.\n lock.lock();\n try {\n while (step != 2) {\n // protect against spurious wakeups.\n secondThread.await(); \n }\n printSecond.run();\n thirdThread.signal();\n step = 3;\n } finally {\n lock.unlock();\n }\n }\n\n public void third(Runnable printThird) throws InterruptedException {\n \n // printThird.run() outputs "third". Do not change or remove this line.\n lock.lock();\n try {\n while (step !=3) {\n // protect against spurious wakeups.\n thirdThread.await();\n }\n printThird.run();\n } finally {\n lock.unlock();\n }\n }\n}\n```
3
0
[]
0
print-in-order
Simple java solution
simple-java-solution-by-wolv_ad-8h2v
Using wait and notifyAll to print in order. \n``` \nvolatile int loc = 0;\n public Foo() {\n loc = 0; \n }\n\n public void first(Runnable printF
wolv_ad
NORMAL
2021-04-29T18:31:28.478010+00:00
2021-04-29T18:31:28.478050+00:00
564
false
Using wait and notifyAll to print in order. \n``` \nvolatile int loc = 0;\n public Foo() {\n loc = 0; \n }\n\n public void first(Runnable printFirst) throws InterruptedException {\n \n // printFirst.run() outputs "first". Do not change or remove this line.\n synchronized(this){\n while(loc != 0){\n this.wait();\n }\n loc = (loc + 1) % 3;\n this.notifyAll();\n printFirst.run();\n }\n }\n\n public void second(Runnable printSecond) throws InterruptedException {\n \n // printSecond.run() outputs "second". Do not change or remove this line.\n synchronized(this){\n while(loc != 1){\n this.wait();\n }\n loc = (loc + 1) % 3;\n this.notifyAll();\n printSecond.run();\n }\n }\n\n public void third(Runnable printThird) throws InterruptedException {\n \n // printThird.run() outputs "third". Do not change or remove this line.\n synchronized(this){\n while(loc != 2){\n this.wait();\n }\n loc = (loc + 1) % 3;\n this.notifyAll();\n printThird.run();\n }\n }
3
0
[]
1
print-in-order
C++ MUTEX AND CONDITION VARIABLE 12MS
c-mutex-and-condition-variable-12ms-by-a-9tr6
\nclass Foo {\n mutex m;\n condition_variable firstCond;\n condition_variable secondCond;\n condition_variable thirdCond;\n int chance;\npublic:\
abhi_tom
NORMAL
2021-04-11T04:37:51.030285+00:00
2021-04-11T04:37:51.030320+00:00
346
false
```\nclass Foo {\n mutex m;\n condition_variable firstCond;\n condition_variable secondCond;\n condition_variable thirdCond;\n int chance;\npublic:\n Foo() {\n chance=1;\n }\n\n void first(function<void()> printFirst) {\n unique_lock<mutex> locker(m);\n \n firstCond.wait(locker,[&](){\n return chance==1;\n });\n \n // printFirst() outputs "first". Do not change or remove this line.\n printFirst();\n \n chance=2;\n secondCond.notify_one();\n }\n\n void second(function<void()> printSecond) {\n unique_lock<mutex> locker(m);\n \n secondCond.wait(locker,[&](){\n return chance==2;\n });\n \n // printSecond() outputs "second". Do not change or remove this line.\n printSecond();\n \n chance=3;\n thirdCond.notify_one();\n }\n\n void third(function<void()> printThird) {\n unique_lock<mutex> locker(m);\n \n thirdCond.wait(locker,[&](){\n return chance==3;\n });\n \n // printThird() outputs "third". Do not change or remove this line.\n printThird();\n }\n};\n```
3
0
[]
0
print-in-order
[C++] simple atomics with memory order
c-simple-atomics-with-memory-order-by-ba-5eyx
\nclass Foo {\npublic:\n Foo() {\n \n }\n\n void first(function<void()> printFirst) {\n printFirst();\n a1.store(true, memory_orde
batmad
NORMAL
2021-03-23T01:54:25.623473+00:00
2021-03-23T01:54:25.623515+00:00
542
false
```\nclass Foo {\npublic:\n Foo() {\n \n }\n\n void first(function<void()> printFirst) {\n printFirst();\n a1.store(true, memory_order_release);\n }\n\n void second(function<void()> printSecond) {\n while(!a1.load(std::memory_order_acquire)) this_thread::yield();\n printSecond();\n a2.store(true, memory_order_release);\n }\n\n void third(function<void()> printThird) {\n while(!a2.load(std::memory_order_acquire)) this_thread::yield();\n printThird();\n }\nprivate:\n atomic<bool> a1{false};\n atomic<bool> a2{false};\n};\n```
3
0
['C']
0
print-in-order
c++ using semaphores - short with comments
c-using-semaphores-short-with-comments-b-l6yy
\n#include <semaphore.h>\nclass Foo {\n sem_t firstSem;\n sem_t secondSem;\npublic:\n Foo() {\n\t//init two semaphores with counter = 0\n sem_in
ofir_kr
NORMAL
2021-02-08T10:40:31.320244+00:00
2021-02-08T10:46:15.968911+00:00
374
false
```\n#include <semaphore.h>\nclass Foo {\n sem_t firstSem;\n sem_t secondSem;\npublic:\n Foo() {\n\t//init two semaphores with counter = 0\n sem_init(&firstSem, 0, 0);\n sem_init(&secondSem, 0, 0);\n }\n\n void first(function<void()> printFirst) {\n \n // printFirst() outputs "first". Do not change or remove this line.\n printFirst();\n sem_post(&firstSem); //increase firstSem counter to one to indicate printFirst() was finish \n }\n\n void second(function<void()> printSecond) {\n sem_wait(&firstSem); //wait for printFirst() to finish\n // printSecond() outputs "second". Do not change or remove this line.\n printSecond();\n sem_post(&secondSem); //increase secondSem counter to one to indicate printSecond() was finish \n }\n\n void third(function<void()> printThird) {\n sem_wait(&secondSem); //wait for printSecond() to finish\n // printThird() outputs "third". Do not change or remove this line.\n printThird();\n }\n};\n```
3
0
['C']
3
print-in-order
C++ condition variable clean code easy to understand
c-condition-variable-clean-code-easy-to-rb5oi
C++\nclass Foo {\n atomic<int> cur;\n mutex mtx;\n condition_variable cv;\nprotected:\n void do_work(function<void()> printS, function<bool()> check
lzqgeorge
NORMAL
2021-01-25T01:18:11.797415+00:00
2021-01-25T01:18:11.797451+00:00
740
false
```C++\nclass Foo {\n atomic<int> cur;\n mutex mtx;\n condition_variable cv;\nprotected:\n void do_work(function<void()> printS, function<bool()> check) {\n std::unique_lock<mutex> lk(mtx);\n cv.wait(lk, [&]{return check();});\n \n cur = (cur+1)%4;\n printS();\n cv.notify_all();\n }\n \npublic:\n Foo() {\n this->cur = 1;\n }\n\n void first(function<void()> printFirst) {\n // printFirst() outputs "first". Do not change or remove this line.\n do_work(printFirst, [&]{return cur == 1;});\n }\n\n void second(function<void()> printSecond) {\n // printSecond() outputs "second". Do not change or remove this line.\n do_work(printSecond, [&]{return cur == 2;});\n }\n\n void third(function<void()> printThird) {\n \n // printThird() outputs "third". Do not change or remove this line.\n do_work(printThird, [&]{return cur == 3;});\n }\n};\n```
3
0
['C', 'C++']
0
print-in-order
C# Monitor Wait & PulseAll
c-monitor-wait-pulseall-by-1988hz-y1ke
\nusing System.Threading; \n\npublic class Foo\n {\n class Lock\n {\n public int Step;\n }\n\n static Lock _Lock = new
1988hz
NORMAL
2021-01-10T03:43:07.864863+00:00
2021-01-10T03:43:07.864889+00:00
249
false
```\nusing System.Threading; \n\npublic class Foo\n {\n class Lock\n {\n public int Step;\n }\n\n static Lock _Lock = new Lock(){ Step = 0 };\n\n public Foo()\n {\n\n }\n\n public void First(Action printFirst)\n {\n lock (_Lock)\n {\n // printFirst() outputs "first". Do not change or remove this line.\n printFirst();\n _Lock.Step = 1;\n Monitor.PulseAll(_Lock);\n }\n }\n\n public void Second(Action printSecond)\n {\n lock (_Lock)\n {\n while (_Lock.Step!= 1)\n {\n Monitor.Wait(_Lock);\n }\n // printSecond() outputs "second". Do not change or remove this line.\n printSecond();\n _Lock.Step = 2;\n Monitor.PulseAll(_Lock);\n }\n }\n\n public void Third(Action printThird)\n {\n lock (_Lock)\n {\n while(_Lock.Step!=2)\n {\n Monitor.Wait(_Lock);\n }\n // printThird() outputs "third". Do not change or remove this line. \n printThird();\n _Lock.Step = 3;\n Monitor.PulseAll(_Lock);\n }\n }\n }\n```
3
1
[]
0
print-in-order
Python solution without using additional libraries
python-solution-without-using-additional-463f
\nclass Foo:\n def __init__(self):\n self._first = False\n self._second = False\n\n\n def first(self, printFirst: \'Callable[[], None]\') ->
bluebadger
NORMAL
2020-12-06T01:49:06.473200+00:00
2020-12-06T01:49:06.473225+00:00
469
false
```\nclass Foo:\n def __init__(self):\n self._first = False\n self._second = False\n\n\n def first(self, printFirst: \'Callable[[], None]\') -> None:\n \n # printFirst() outputs "first". Do not change or remove this line.\n printFirst()\n self._first = True\n\n\n def second(self, printSecond: \'Callable[[], None]\') -> None:\n while not self._first:\n pass\n \n # printSecond() outputs "second". Do not change or remove this line.\n printSecond()\n self._second = True\n\n\n def third(self, printThird: \'Callable[[], None]\') -> None:\n while not self._second:\n pass\n # printThird() outputs "third". Do not change or remove this line.\n printThird()\n```
3
0
[]
0
print-in-order
CountDownLatch Java
countdownlatch-java-by-_gauravgupta-bgjq
\nclass Foo {\n\n private CountDownLatch latch1 = new CountDownLatch(1);\n private CountDownLatch latch2 = new CountDownLatch(1);\n \n public Foo() {\
_gauravgupta
NORMAL
2020-11-19T17:26:26.367809+00:00
2020-11-19T17:26:26.367839+00:00
216
false
```\nclass Foo {\n\n private CountDownLatch latch1 = new CountDownLatch(1);\n private CountDownLatch latch2 = new CountDownLatch(1);\n \n public Foo() {\n \n }\n\n public void first(Runnable printFirst) throws InterruptedException {\n \n // printFirst.run() outputs "first". Do not change or remove this line.\n printFirst.run();\n latch1.countDown();\n }\n\n public void second(Runnable printSecond) throws InterruptedException {\n \n latch1.await();\n // printSecond.run() outputs "second". Do not change or remove this line.\n printSecond.run();\n latch2.countDown();\n \n }\n\n public void third(Runnable printThird) throws InterruptedException {\n // printThird.run() outputs "third". Do not change or remove this line.\n latch2.await();\n printThird.run();\n }\n}\n```
3
0
[]
0
print-in-order
C++ Solution Using 2 mutexes
c-solution-using-2-mutexes-by-yehudisk-gtz4
\nclass Foo {\npublic:\n Foo() {\n pthread_mutex_lock(&m_second);\n pthread_mutex_lock(&m_third);\n }\n \n ~Foo() {\n pthread_m
yehudisk
NORMAL
2020-11-18T23:26:48.431768+00:00
2020-11-18T23:26:48.431809+00:00
221
false
```\nclass Foo {\npublic:\n Foo() {\n pthread_mutex_lock(&m_second);\n pthread_mutex_lock(&m_third);\n }\n \n ~Foo() {\n pthread_mutex_destroy(&m_second);\n pthread_mutex_destroy(&m_third);\n }\n\n void first(function<void()> printFirst) {\n \n // printFirst() outputs "first". Do not change or remove this line.\n printFirst();\n pthread_mutex_unlock(&m_second);\n }\n\n void second(function<void()> printSecond) {\n \n // printSecond() outputs "second". Do not change or remove this line.\n pthread_mutex_lock(&m_second);\n printSecond();\n pthread_mutex_unlock(&m_third);\n }\n\n void third(function<void()> printThird) {\n \n // printThird() outputs "third". Do not change or remove this line.\n pthread_mutex_lock(&m_third);\n printThird();\n }\nprivate:\n pthread_mutex_t m_second = PTHREAD_MUTEX_INITIALIZER;\n pthread_mutex_t m_third = PTHREAD_MUTEX_INITIALIZER;\n};\n```
3
0
[]
0
print-in-order
Java | Semaphore simple implementation
java-semaphore-simple-implementation-by-xa7y4
\nclass Foo {\n \n Semaphore second = new Semaphore(0);\n Semaphore third = new Semaphore(0);\n\n public Foo() {\n \n }\n\n public void
onesubhadip
NORMAL
2020-09-17T11:11:01.486801+00:00
2020-09-17T11:11:01.486843+00:00
384
false
```\nclass Foo {\n \n Semaphore second = new Semaphore(0);\n Semaphore third = new Semaphore(0);\n\n public Foo() {\n \n }\n\n public void first(Runnable printFirst) throws InterruptedException {\n \n // printFirst.run() outputs "first". Do not change or remove this line.\n printFirst.run();\n second.release();\n }\n\n public void second(Runnable printSecond) throws InterruptedException {\n \n second.acquire();\n // printSecond.run() outputs "second". Do not change or remove this line.\n printSecond.run();\n third.release();\n }\n\n public void third(Runnable printThird) throws InterruptedException {\n \n third.acquire();\n // printThird.run() outputs "third". Do not change or remove this line.\n printThird.run();\n }\n}\n```
3
0
[]
1
print-in-order
[C++] 132ms/7.2MB using std::condition_variable in a proper way
c-132ms72mb-using-stdcondition_variable-ewlxr
Example with test cases\nhttps://github.com/jimmy-park/leetcode-cpp-solution/blob/master/Concurrency/1114-Print-in-Order.h\n\n\nclass Foo {\npublic:\n void f
jiwoo_90
NORMAL
2020-07-26T20:47:26.001102+00:00
2020-07-30T11:34:50.724009+00:00
675
false
Example with test cases\nhttps://github.com/jimmy-park/leetcode-cpp-solution/blob/master/Concurrency/1114-Print-in-Order.h\n\n```\nclass Foo {\npublic:\n void first(function<void()> printFirst)\n {\n // printFirst() outputs "first". Do not change or remove this line.\n printFirst();\n\n {\n // prevent lost wakeup and spurious wakeup\n // and with CTAD (since C++17), you don\'t need to type std::mutex as template argument\n std::lock_guard lock { mutex_ };\n done_first_ = true;\n }\n\n cv_.notify_all();\n }\n\n void second(function<void()> printSecond)\n {\n {\n std::unique_lock lock { mutex_ };\n cv_.wait(lock, [this] { return done_first_; });\n }\n\n // printSecond() outputs "second". Do not change or remove this line.\n printSecond();\n\n {\n std::lock_guard lock { mutex_ };\n done_second_ = true;\n }\n \n cv_.notify_one();\n }\n\n void third(function<void()> printThird)\n {\n {\n std::unique_lock lock { mutex_ };\n cv_.wait(lock, [this] { return done_second_; });\n }\n\n // printThird() outputs "third". Do not change or remove this line.\n printThird();\n }\n\nprivate:\n bool done_first_ { false };\n bool done_second_ { false };\n mutable std::mutex mutex_;\n std::condition_variable cv_;\n};\n```
3
0
['C', 'C++']
2
print-in-order
Py soln using sleep(), simple and fast
py-soln-using-sleep-simple-and-fast-by-z-g8mf
This simple solution was faster than 95.4% solutiions (32ms runtime)\n\n\n\nclass Foo:\n#flag variables \n calledFirst = 0\n calledSecond = 0\n def __i
zwicky
NORMAL
2020-07-19T12:41:14.834222+00:00
2020-07-19T13:10:16.267415+00:00
217
false
This simple solution was faster than 95.4% solutiions (32ms runtime)\n```\n\n\nclass Foo:\n#flag variables \n calledFirst = 0\n calledSecond = 0\n def __init__(self):\n pass\n\n\n def first(self, printFirst: \'Callable[[], None]\') -> None:\n \n #print and set flag\n printFirst()\n self.calledFirst = 1\n\n\n def second(self, printSecond: \'Callable[[], None]\') -> None:\n\t#wait for 0.01s and then check for the condition again \n while(not self.calledFirst):\n time.sleep(0.01)\n printSecond()\n\t\t#flag for second function\n self.calledSecond = 1\n \n\n def third(self, printThird: \'Callable[[], None]\') -> None:\n \n while(not self.calledSecond): \n time.sleep(0.01)\n printThird()\n \n \n```
3
1
['Python3']
0
groups-of-special-equivalent-strings
Java Concise Set Solution
java-concise-set-solution-by-caraxin-xpjx
For each String, we generate it\'s corresponding signature, and add it to the set.\nIn the end, we return the size of the set.\n\nclass Solution {\n public i
caraxin
NORMAL
2018-08-26T03:01:07.888583+00:00
2018-10-24T13:36:01.151927+00:00
8,332
false
For each String, we generate it\'s corresponding signature, and add it to the set.\nIn the end, we return the size of the set.\n```\nclass Solution {\n public int numSpecialEquivGroups(String[] A) {\n Set<String> set= new HashSet<>();\n for (String s: A){\n int[] odd= new int[26];\n int[] even= new int[26];\n for (int i=0; i<s.length(); i++){\n if (i%2==1) odd[s.charAt(i)-\'a\']++;\n else even[s.charAt(i)-\'a\']++;\n }\n String sig= Arrays.toString(odd)+Arrays.toString(even);\n set.add(sig);\n }\n return set.size();\n }\n}\n```
127
0
[]
11
groups-of-special-equivalent-strings
Python 1-liner
python-1-liner-by-cenkay-8oeu
\nclass Solution:\n def numSpecialEquivGroups(self, A):\n return len(set("".join(sorted(s[0::2])) + "".join(sorted(s[1::2])) for s in A))\n
cenkay
NORMAL
2018-08-26T07:38:06.658961+00:00
2018-09-23T04:15:55.200241+00:00
4,589
false
```\nclass Solution:\n def numSpecialEquivGroups(self, A):\n return len(set("".join(sorted(s[0::2])) + "".join(sorted(s[1::2])) for s in A))\n```
58
1
[]
7
groups-of-special-equivalent-strings
C++ Simple Solution
c-simple-solution-by-code_report-hkzn
General Idea:\n\n1. Split strings in two to substrings, 1 with even indexed characters, and 1 with odd\n2. Sort the two substrings (We do this because if you ca
code_report
NORMAL
2018-08-26T03:01:07.733763+00:00
2018-09-24T03:47:39.591039+00:00
6,221
false
**General Idea:**\n\n1. Split strings in two to substrings, 1 with even indexed characters, and 1 with odd\n2. Sort the two substrings (We do this because if you can swap on string with another, when sorted they will equal each other because they must have the same characters)\n3. Insert your pair of strings into set, this will keep track of the unique "groups"\n4. Rerturn the size of your set\n\nCheck out the video solution and explanation (for C++, Java, Python and BASH) here: https://youtu.be/WJ4NtyrakT0\n```\nint numSpecialEquivGroups(vector<string>& A) {\n set<pair<string,string>> s;\n for (const auto& w : A) {\n pair<string,string> p;\n for (int i = 0; i < w.size (); ++i) {\n if (i % 2) p.first += w[i];\n else p.second += w[i];\n }\n sort (p.first.begin (), p.first.end ());\n sort (p.second.begin (), p.second.end ());\n s.insert (p);\n }\n return s.size ();\n}
55
0
[]
8
groups-of-special-equivalent-strings
[python3] detail explanation of special-equivalent
python3-detail-explanation-of-special-eq-x5ng
The point here is to understand the following requirement:\nA move consists of choosing two indices i and j with i % 2 == j % 2, and swapping S[i] with S[j].\nD
zhanweiting
NORMAL
2019-08-14T22:40:16.726298+00:00
2019-08-14T22:44:39.425253+00:00
1,785
false
* The point here is to understand the following requirement:\nA move consists of choosing two indices i and j with i % 2 == j % 2, and swapping S[i] with S[j].\nDon\'t trap your thoughts by the word \'swap\'.\nYour goal is how to identify the equivalent strings. \n* There are two possible outcomes of i%2: 1 or 0. i is the index of the input string.\n\tif i % 2 ==1: i = 1,3,5,7 ... in other words, i is odd number. In other words, the order of the odd index\'s value doesn\'t matter here. You can swap them.\n\tif i % 2 ==0: i = 0,2,4,6 ... in other words, i is even number. In other words, the order of the even index\'s value doesn\'t matter here. You can swap them.\n* So sort the string\'s odd index elements, and sort the string\'s even index elements and combine them to create a new string called "sort_string." If two string has the same "sort_string," they are the special-equivalent strings.\n```\nA = ["abcd","cdab","adcb","cbad"]\n ### sort odd index element | sort even index element\n"abcd" : bd | ac\n"cbad" : bd | ac\n"adcb" : bd | ac\n"cdab" : bd | ac\n# so they are equivalent strings\n```\n\n```\nclass Solution:\n def numSpecialEquivGroups(self, A: List[str]) -> int:\n res = set()\n for s in A:\n sort_odd_even = \'\'.join(sorted(s[1::2]) + sorted(s[::2]))\n res.add(sort_odd_even)\n return len(res)\n```
40
0
['Python', 'Python3']
3
groups-of-special-equivalent-strings
Python extremely simple solution
python-extremely-simple-solution-by-wnmm-6x6b
\nclass Solution:\n\tdef numSpecialEquivGroups(self, A):\n\t\td = collections.defaultdict(int)\n\t\tfor w in A:\n\t\t\teven = \'\'.join(sorted(w[0::2]))\n\t\t\t
wnmmxy
NORMAL
2018-08-26T04:02:20.715408+00:00
2018-09-05T06:19:55.777489+00:00
2,164
false
```\nclass Solution:\n\tdef numSpecialEquivGroups(self, A):\n\t\td = collections.defaultdict(int)\n\t\tfor w in A:\n\t\t\teven = \'\'.join(sorted(w[0::2]))\n\t\t\todd = \'\'.join(sorted(w[1::2]))\n\t\t\td[(even, odd)] += 1\n\t\t\n\t\treturn len(d)\n```
21
1
[]
4
groups-of-special-equivalent-strings
Straightforward Java solution
straightforward-java-solution-by-mycafeb-53p3
map1 - the distribution of counts of the characters at even positions\nmap2 - the distribution of counts of the characters at odd positions\nset - how many uniq
mycafebabe
NORMAL
2018-08-27T02:35:27.727517+00:00
2018-10-09T07:50:16.784070+00:00
1,499
false
map1 - the distribution of counts of the characters at even positions\nmap2 - the distribution of counts of the characters at odd positions\nset - how many unique distributions\n\n```\nclass Solution {\n public int numSpecialEquivGroups(String[] A) {\n Set<String> set = new HashSet<>();\n for (String s : A) {\n int[] map1 = new int[256];\n int[] map2 = new int[256];\n for (int i = 0; i < s.length(); i++) {\n if (i % 2 == 0) {\n map1[s.charAt(i)]++;\n } else {\n map2[s.charAt(i)]++;\n }\n }\n set.add(Arrays.toString(map1) + " " + Arrays.toString(map2));\n }\n return set.size();\n }\n}\n```
11
1
[]
1
groups-of-special-equivalent-strings
Python 3 || 5 lines, w/ example || T/S: 84% / 16%
python-3-5-lines-w-example-ts-84-16-by-s-35jj
\n\nclass Solution:\n def numSpecialEquivGroups(self, words: List[str]) -> int:\n # Example: \n
Spaulding_
NORMAL
2022-12-21T23:44:54.279178+00:00
2024-05-31T05:14:59.247328+00:00
791
false
\n```\nclass Solution:\n def numSpecialEquivGroups(self, words: List[str]) -> int:\n # Example: \n wSet = set() # words = ["abc","acb","bac","bca","cab","cba"]\n\n for word in words: # sorted((enu- \n word = tuple(sorted((enumerate(word)), # word merate word) wSet\n key = lambda x: (x[0]%2,x[1]))) # \u2013\u2013\u2013\u2013\u2013 \u2013\u2013\u2013\u2013\u2013\u2013\u2013\u2013\u2013\u2013\u2013\u2013 \u2013\u2013\u2013\u2013\u2013\u2013\u2013\u2013\u2013\u2013\u2013\u2013\u2013\u2013\n # abc ((0,a),(2,c),(1,b)) {(a,c,b)}\n wSet.add(list(zip(*word))[1]) # acb ((0,a),(2,b),(1,c)) {(a,c,b), (a,b,c)}\n # bac ((0,b),(2,c),(1,a)) {(a,c,b), (a,b,c), (b,c,a)}\n return len(wSet) # bca ((2,a),(0,b),(1,c)) {(a,c,b), (a,b,c), (b,c,a)}\n # cab ((2,b),(0,c),(1,a)) {(a,c,b), (a,b,c), (b,c,a)}\n # cba ((2,a),(0,c),(1,b)) {(a,c,b), (a,b,c), (b,c,a)}\n```\n[https://leetcode.com/problems/groups-of-special-equivalent-strings/submissions/1272965481/](https://leetcode.com/problems/groups-of-special-equivalent-strings/submissions/1272965481/)\n\n\nI could be wrong, but I think that time is *O*(*NlogN*) and space is *O*(*N*).
8
0
['Python3']
0
groups-of-special-equivalent-strings
Python O(n * k lg k) sol. by signature. 90%+ [w/ Hint]
python-on-k-lg-k-sol-by-signature-90-w-h-z5ep
Python sol. by signature. \n\n---\n\nHint:\n\nThink of the concept for anagram judgement.\n\nWhat we need in this challenge is to verify the so-called "special
brianchiang_tw
NORMAL
2020-03-11T11:34:35.114132+00:00
2020-03-11T15:08:22.987904+00:00
857
false
Python sol. by signature. \n\n---\n\n**Hint**:\n\nThink of the concept for **anagram** judgement.\n\nWhat we need in this challenge is to verify the so-called "**special equivalent**", \nwhich means even-indexed substring of input is anagram and odd-indexed substring of input is another anagram.\n\nWe can verify by signature checking.\n\nDefine **signature** as the **sorted even-indexed substring and odd-indexed substring** in alphabetic order.\n\nIf signature( s1 ) == signature( s2 ),\nthen s1 and s2 are special equivalent.\n\n---\n\nFor example:\ns1 = \'**a**b**c**d\', and s2 = \'**c**d**a**b\'\n\nThen, signature( s1 ) is \'acbd\', and signature( s2 ) is the same.\nTherefore, s1 and s2 are special equivalent.\n\n---\n\n**Algorithm**:\n\nRearrange each input string into the form of signature.\n\nThe **number of unique signature** is the **number of grouping** for special equivalent.\n\n---\n\n**Implementation**:\n```\nclass Solution:\n def numSpecialEquivGroups(self, A: List[str]) -> int:\n \n signature = set()\n \n # Use pair of sorted even substring and odd substring as unique key\n \n for idx, s in enumerate(A):\n signature.add( \'\'.join( sorted( s[::2] ) ) + \'\'.join( sorted( s[1::2] ) ) )\n \n return len( signature )\n```\n\n---\n\nRelated challenge:\n\n[Leetcode #49 Group Anagrms](https://leetcode.com/problems/group-anagrams/)\n\n[Leetcode #242 Valid Anagram](https://leetcode.com/problems/valid-anagram/)\n\n[Leetcode #438 Find All Anagrams in a String](https://leetcode.com/problems/find-all-anagrams-in-a-string/)\n\n---\n\nReference:\n\n[1] [Python official docs about hash-set: set()](https://docs.python.org/3/tutorial/datastructures.html#sets)
8
0
['Ordered Set', 'Python', 'Python3']
2
groups-of-special-equivalent-strings
Python 1-liner (beats 100% of other submissions)
python-1-liner-beats-100-of-other-submis-dvd3
The idea is to convert all strings to some sort of canonical representation. Since all characters at even and odd position can be shuffled in any way, sorting t
ttsugrii
NORMAL
2018-08-29T06:33:18.404330+00:00
2018-10-24T22:11:16.299265+00:00
798
false
The idea is to convert all strings to some sort of canonical representation. Since all characters at even and odd position can be shuffled in any way, sorting them will produce the desired result - strings like `cba` will be converted to `abc` and `dcba` to `badc`. Having all strings converted to their canonical form, a set can be used to remove the duplicates and its length will produce the desired result.\n```\nclass Solution:\n def numSpecialEquivGroups(self, A):\n """\n :type A: List[str]\n :rtype: int\n """\n return len({tuple(sorted(s[0::2]) + sorted(s[1::2])) for s in A})\n```
7
1
[]
0
groups-of-special-equivalent-strings
C++||Set||Easy to Understand
cseteasy-to-understand-by-return_7-8qf2
```\nclass Solution {\npublic:\n int numSpecialEquivGroups(vector& words)\n { \n set> s;\n for(auto &w:words)\n {\n str
return_7
NORMAL
2022-08-15T22:36:21.178258+00:00
2022-08-15T22:36:21.178293+00:00
441
false
```\nclass Solution {\npublic:\n int numSpecialEquivGroups(vector<string>& words)\n { \n set<pair<string,string>> s;\n for(auto &w:words)\n {\n string p,q;\n for(int i=0;i<w.size();i++)\n {\n if(i%2==0)\n {\n p+=w[i];\n }\n else\n {\n q+=w[i];\n }\n }\n sort(p.begin(),p.end());\n sort(q.begin(),q.end());\n s.insert({p,q});\n }\n return s.size();\n }\n};\n//if you like the solution plz upvote.
6
0
['C', 'Ordered Set']
1
groups-of-special-equivalent-strings
JavaScript easy solution
javascript-easy-solution-by-shengdade-yt3g
javascript\n/**\n * @param {string[]} A\n * @return {number}\n */\nvar numSpecialEquivGroups = function(A) {\n const groupSet = new Set();\n A.forEach(a => gr
shengdade
NORMAL
2020-02-17T22:39:31.755963+00:00
2020-02-17T22:39:31.755999+00:00
433
false
```javascript\n/**\n * @param {string[]} A\n * @return {number}\n */\nvar numSpecialEquivGroups = function(A) {\n const groupSet = new Set();\n A.forEach(a => groupSet.add(transform(a)));\n return groupSet.size;\n};\n\nconst transform = S => {\n const even = S.split(\'\').filter((_, i) => i % 2 === 0);\n const odd = S.split(\'\').filter((_, i) => i % 2 === 1);\n even.sort();\n odd.sort();\n return `${even.join(\'\')}${odd.join(\'\')}`;\n};\n```\n\n* 36/36 cases passed (64 ms)\n* Your runtime beats 100 % of javascript submissions\n* Your memory usage beats 100 % of javascript submissions (37.5 MB)
6
0
['JavaScript']
0
groups-of-special-equivalent-strings
C# using counting sort since string contains English letters
c-using-counting-sort-since-string-conta-fp3p
Sept. 23, 2018\nIt is an easy level string algorithm. The swap of letters should be restricted to odd index or even index two groups. All letters in odd index c
jianminchen
NORMAL
2018-09-24T03:56:02.013592+00:00
2020-08-19T18:47:50.012142+00:00
519
false
Sept. 23, 2018\nIt is an easy level string algorithm. The swap of letters should be restricted to odd index or even index two groups. All letters in odd index can be swapped, likewise as even index. \n\n```\npublic class Solution {\n public int NumSpecialEquivGroups(string[] A)\n {\n if (A == null)\n return 0;\n\n var keys = new HashSet<string>(); \n\n foreach(var item in A)\n {\n var countLetterEven = new int[26];\n var countLetterOdd = new int[26];\n\n for (int i = 0; i < item.Length; i++ )\n {\n var current = item[i];\n var isEven = i % 2 == 0;\n if (isEven)\n {\n countLetterEven[current - \'a\']++;\n }\n else\n countLetterOdd[current - \'a\']++; \n }\n\n var key = createKey(countLetterEven, countLetterOdd);\n if (!keys.Contains(key))\n keys.Add(key);\n }\n\n return keys.Count; \n }\n\n private static string createKey(int[] even, int[] odd)\n {\n var key = "";\n for(int i = 0; i < 26; i++)\n {\n key += even[i] + " " + odd[i] +";";\n }\n\n return key; \n }\n}\n```\n
6
1
[]
0
groups-of-special-equivalent-strings
[C++] Create a signature for each string
c-create-a-signature-for-each-string-by-6cvp6
We can quickly notice that by grouping odd and even position, sorting them and concatenating them, all the special - equivalent string will have the same signat
facelessvoid
NORMAL
2018-08-27T12:47:04.554745+00:00
2018-09-25T07:46:52.493984+00:00
876
false
We can quickly notice that by grouping odd and even position, sorting them and concatenating them, all the special - equivalent string will have the same signature. We can then use a hash set to capture the signature (which automatically de-duplicates) and we can return the hashset size.\nThe constraints of the problem easily allow this.\n```\nclass Solution {\npublic:\n int numSpecialEquivGroups(vector<string>& A) {\n unordered_set<string> st;\n for(auto &w : A) {\n string odd, even;\n for(int i=0;i<w.size();i+=2) even.push_back(w[i]);\n for(int i=1;i<w.size();i+=2) odd.push_back(w[i]);\n sort(odd.begin(), odd.end());\n sort(even.begin(), even.end());\n st.insert(even + odd);\n }\n return st.size();\n }\n};\n```
6
0
[]
1
groups-of-special-equivalent-strings
Set || Easy C++ || Clean Code ✅✅
set-easy-c-clean-code-by-deepak_5910-tw73
Approach\n Describe your approach to solving the problem. \nAfter sorting the even and odd Position characters of a string put it into a unordered set and final
Deepak_5910
NORMAL
2023-08-10T04:34:09.631710+00:00
2023-08-10T04:34:09.631736+00:00
301
false
# Approach\n<!-- Describe your approach to solving the problem. -->\nAfter **sorting** the **even and odd Position characters** of a string put it into a **unordered set** and finally return the **size** of the set.\n\n# Complexity\n- Time complexity:O(N * 20 * 10 * Log(10))\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 int numSpecialEquivGroups(vector<string>& w) {\n unordered_set<string> st;\n for(int i = 0;i<w.size();i++)\n {\n string even = "",odd = "";\n for(int j = 0;j<w[i].size();j++)\n {\n if(j%2) odd+=w[i][j];\n else even+=w[i][j];\n }\n sort(even.begin(),even.end());\n sort(odd.begin(),odd.end());\n st.insert(even+odd);\n }\n return st.size();\n \n }\n};\n```\n![upvote.jpg](https://assets.leetcode.com/users/images/a09140aa-537b-4890-9c3c-1f7ab2a60bab_1691642025.638834.jpeg)\n
5
0
['C++']
0
groups-of-special-equivalent-strings
BUG IN LEETCODE ITSELF!!!! CHECK IT OUT... LOL
bug-in-leetcode-itself-check-it-out-lol-70hv4
\n\nSubmission tab gives wrong answer and output 5. But Debug tab (and my IDE) has correct answer 1. \n\nSolution:\n\nclass Solution {\n public int numSpecia
ssemichev
NORMAL
2019-08-16T06:27:36.353520+00:00
2019-11-18T06:40:13.883157+00:00
566
false
![image](https://assets.leetcode.com/users/ssemichev/image_1565936717.png)\n![image](https://assets.leetcode.com/users/ssemichev/image_1565936718.png)\nSubmission tab gives wrong answer and output 5. But Debug tab (and my IDE) has correct answer 1. \n\nSolution:\n```\nclass Solution {\n public int numSpecialEquivGroups(String[] input) {\n int[] inx = new int[input.length];\n int group = 1;\n for(int i = 0; i < input.length; i++){\n if(inx[i] != 0) continue;\n inx[i] = group++;\n for(int j = i + 1; j < input.length; j++ ) {\n if (j != 0 && eq(input[i], input[j])) {\n inx[i] = group;\n inx[j] = group;\n }\n }\n }\n return group - 1;\n }\n \n private boolean eq(String a, String b){\n if(a.equals(b)) return true;\n \n char[] buff = b.toCharArray();\n for(int i = 0; i < buff.length; i++){\n int j = i + 2;\n while(j < buff.length && (i % 2 != j % 2)) j++;\n if(j < buff.length){\n if(buff[i] == a.charAt(i) && buff[j] == a.charAt(j)) continue;\n char t = buff[i];\n buff[i] = buff[j];\n buff[j] = t;\n if(a.equals(new String(buff)))\n return true;\n }\n }\n return false;\n }\n}\n```
5
0
[]
1
groups-of-special-equivalent-strings
(C++) 893. Groups of Special-Equivalent Strings
c-893-groups-of-special-equivalent-strin-lefd
\n\nclass Solution {\npublic:\n int numSpecialEquivGroups(vector<string>& A) {\n unordered_set<string> seen; \n for (auto word : A) {\n
qeetcode
NORMAL
2021-04-17T02:54:26.391804+00:00
2021-04-17T02:54:26.391833+00:00
383
false
\n```\nclass Solution {\npublic:\n int numSpecialEquivGroups(vector<string>& A) {\n unordered_set<string> seen; \n for (auto word : A) {\n string even, odd; \n for (int i = 0; i < word.size(); ++i) {\n if (i&1) odd.push_back(word[i]); \n else even.push_back(word[i]); \n }\n sort(even.begin(), even.end()); \n sort(odd.begin(), odd.end()); \n seen.insert(even+odd); \n }\n return seen.size(); \n }\n};\n```
4
0
['C']
0
groups-of-special-equivalent-strings
[typescript/javascript] o(n) solution w/ detailed comments + explanation
typescriptjavascript-on-solution-w-detai-9f72
Forget what the problem is asking for a second. I\'ll dumb it down. It took me too long and I overthought way too hard.\nShout out to Fisher Coder (on youtube)
carti
NORMAL
2020-09-23T05:24:35.415703+00:00
2020-09-23T05:24:35.415758+00:00
182
false
Forget what the problem is asking for a second. I\'ll dumb it down. It took me too long and I overthought way too hard.\n*Shout out to Fisher Coder (on youtube) for explaining the problem statement. He\'s a legendary beast.*\n\nThe problem is **simply** asking how many strings are distinct, given you can swap any even-indexed characters, and swap any odd-indexed characters.\n\nExample: if you have **"axbycz"** and **"czbyax"**, these ARE specially EQUIVALENT. here is the reasoning: for odd index, we have counts {a: 1, b: 1, c:1} in both of them, and for even index we have {x: 1, y: 1, z: 1} for both of them.\n\n**solution:**\n```\nfunction numSpecialEquivGroups(A: string[]): number {\n // set to keep track of unique special equivalents\n const set: Set<string> = new Set();\n // iterate thru A\n for (let i = 0; i < A.length; i++) {\n // even and odd char counts\n const counts = [new Uint8Array(26), new Uint8Array(26)];\n // iterate thru this string, and fill counts\n for (let j = 0; j < A[i].length; j++) {\n // fill count on whether even or odd (0 index is even 1 is odd)\n counts[j % 2][A[i].charCodeAt(j) - 97]++;\n }\n // add to set as concatenation of both counts arrays\n set.add(counts[0].join(\'\') + counts[1].join(\'\'));\n }\n\n // result is just size of set (number of unique special equivalents)\n return set.size;\n}\n```\n
4
0
['TypeScript', 'JavaScript']
1
groups-of-special-equivalent-strings
simple cpp solution using set
simple-cpp-solution-using-set-by-bitrish-4b8e
\nclass Solution {\npublic:\n int numSpecialEquivGroups(vector<string>& A) {\n ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);\n
bitrish
NORMAL
2020-07-31T14:21:27.822835+00:00
2020-07-31T14:21:27.822891+00:00
346
false
```\nclass Solution {\npublic:\n int numSpecialEquivGroups(vector<string>& A) {\n ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);\n unordered_set<string>mp;\n for(int i=0;i<A.size();i++)\n {\n string o="";\n string e="";\n for(int j=0;j<A[i].size();j++)\n {\n if(j%2==0)\n e+=A[i][j];\n else\n o+=A[i][j];\n }\n sort(o.begin(),o.end());\n sort(e.begin(),e.end());\n mp.insert(e+o);\n }\n return mp.size();\n }\n};\n\n```
4
1
['C', 'Ordered Set', 'C++']
2
groups-of-special-equivalent-strings
JAVA - Easy to Understand Solution
java-easy-to-understand-solution-by-anub-hmop
\npublic int numSpecialEquivGroups(String[] A) {\n\tHashSet<String> s = new HashSet<>();\n\tfor(String a : A) {\n\t\tint[] odd = new int[26], even = new int[26]
anubhavjindal
NORMAL
2019-11-11T01:01:22.988940+00:00
2019-11-11T01:01:22.988973+00:00
322
false
```\npublic int numSpecialEquivGroups(String[] A) {\n\tHashSet<String> s = new HashSet<>();\n\tfor(String a : A) {\n\t\tint[] odd = new int[26], even = new int[26];\n\t\tfor(int i=0; i<a.length(); i++) {\n\t\t\tif(i%2==0)\n\t\t\t\teven[a.charAt(i)-\'a\']++;\n\t\t\telse\n\t\t\t\todd[a.charAt(i)-\'a\']++;\n\t\t}\n\t\ts.add(Arrays.toString(odd)+Arrays.toString(even));\n\t}\n\treturn s.size();\n}\n```
4
0
[]
0
groups-of-special-equivalent-strings
java 6ms solution, easy to understand with explanation
java-6ms-solution-easy-to-understand-wit-jvnt
The basic idea is putting the signature of each string to a set, then the size of set is the number of groups.\nSince each string only contains lowercase letter
pangeneral
NORMAL
2019-04-09T06:05:12.164280+00:00
2019-04-09T06:05:12.164319+00:00
629
false
The basic idea is putting the signature of each string to a set, then the size of set is the number of groups.\nSince each string only contains lowercase letters, we can use two arrays ```odd[26]``` and ```even[26]``` to represents the frequency of 26 lowercase letters on odd place and even place of a string repectively. \nThe signature of a string is apparently ```Arrays.toString(odd) + Arrays.toString(even)```.\nThe code is as following:\n```\npublic int numSpecialEquivGroups(String[] A) {\n\tSet<String> group = new HashSet<String>();\n\tfor(int i = 0; i < A.length; i++) \n\t\tgroup.add(getSignature(A[i]));\n\treturn group.size();\n}\n\npublic String getSignature(String s) {\n\tint odd[] = new int[26];\n\tint even[] = new int[26];\n\tfor(int i = 0; i < s.length(); i += 2) \n\t\teven[s.charAt(i) - \'a\']++;\n\tfor(int i = 1; i < s.length(); i += 2)\n\t\todd[s.charAt(i) - \'a\']++;\n\tStringBuilder sb = new StringBuilder("");\n\tfor(int i = 0; i < 26; i++)\n\t\tsb.append(odd[i]);\n\tfor(int i = 0; i < 26; i++)\n\t\tsb.append(even[i]);\n\treturn sb.toString();\n}\n```
4
0
['Java']
0
groups-of-special-equivalent-strings
c++ | easy | faster
c-easy-faster-by-venomhighs7-vciu
\n\n# Code\n\nclass Solution {\npublic:\n int numSpecialEquivGroups(vector<string>& A) {\n set<pair<string,string>> s;\n for (const auto& w : A) {\n
venomhighs7
NORMAL
2022-11-08T05:57:11.564554+00:00
2022-11-08T05:57:11.564590+00:00
500
false
\n\n# Code\n```\nclass Solution {\npublic:\n int numSpecialEquivGroups(vector<string>& A) {\n set<pair<string,string>> s;\n for (const auto& w : A) {\n pair<string,string> p;\n for (int i = 0; i < w.size (); ++i) {\n if (i % 2) p.first += w[i];\n else p.second += w[i];\n }\n sort (p.first.begin (), p.first.end ());\n sort (p.second.begin (), p.second.end ());\n s.insert (p);\n }\n return s.size ();\n}\n};\n```
3
0
['C++']
0
groups-of-special-equivalent-strings
Simple C++ Code
simple-c-code-by-prosenjitkundu760-me8y
If you like the implementation then Please help me by increasing my reputation. By clicking the up arrow on the left of my image.\n\nclass Solution {\npublic:\n
_pros_
NORMAL
2022-06-21T02:24:57.160433+00:00
2022-06-21T02:24:57.160476+00:00
180
false
# **If you like the implementation then Please help me by increasing my reputation. By clicking the up arrow on the left of my image.**\n```\nclass Solution {\npublic:\n int numSpecialEquivGroups(vector<string>& words) {\n int n = words.size();\n unordered_map<string, int> um;\n for(string &word : words)\n {\n vector<int> even(26,0);\n vector<int> odd(26,0);\n for(int i = 0; i < word.size(); i++)\n {\n if(i%2==0)\n {\n even[word[i]-\'a\']++;\n }\n else\n {\n odd[word[i]-\'a\']++;\n }\n }\n string str = "";\n for(int i = 0; i < 26; i++)\n {\n str += to_string(even[i]);\n }\n for(int i = 0; i < 26; i++)\n {\n str += to_string(odd[i]);\n }\n um[str]++;\n }\n return um.size();\n }\n};\n```
3
0
[]
0
groups-of-special-equivalent-strings
easy, fast python solution
easy-fast-python-solution-by-pranavgarg0-dfmn
```class Solution:\n def numSpecialEquivGroups(self, A: List[str]) -> int:\n dic={}\n for i in range(len(A)):\n x = \'\'.join(sorted
pranavgarg039
NORMAL
2021-02-20T14:20:44.811352+00:00
2021-02-20T14:20:44.811385+00:00
309
false
```class Solution:\n def numSpecialEquivGroups(self, A: List[str]) -> int:\n dic={}\n for i in range(len(A)):\n x = \'\'.join(sorted(A[i][0::2]))\n y = \'\'.join(sorted(A[i][1::2])) \n if (x+y) not in dic:\n dic[x+y]=1\n else:\n dic[x+y]+=1\n return len(dic)\n
3
0
[]
2
groups-of-special-equivalent-strings
python 3, use defaultdict, 40ms (88.5%)
python-3-use-defaultdict-40ms-885-by-phi-x4ct
\n\nclass Solution:\n def numSpecialEquivGroups(self, A: List[str]) -> int:\n #\n helper = defaultdict(int)\n for string in A:\n
philno
NORMAL
2020-12-06T16:48:13.790118+00:00
2020-12-06T16:48:13.790162+00:00
365
false
\n```\nclass Solution:\n def numSpecialEquivGroups(self, A: List[str]) -> int:\n #\n helper = defaultdict(int)\n for string in A:\n key = "".join(sorted(string[0::2])+sorted(string[1::2]))\n helper[key] += 1\n return len(helper)\n```
3
0
['Python', 'Python3']
0
groups-of-special-equivalent-strings
Python 1 Liner and 5 Liner (for readability) Explained
python-1-liner-and-5-liner-for-readabili-4h8g
Since any even index can be switched with any other even index, and the same is true for any odd index pair, as long as two words share the same multiset of eve
rowe1227
NORMAL
2020-05-19T20:00:40.791001+00:00
2020-05-19T20:02:37.658451+00:00
171
false
Since any even index can be switched with any other even index, and the same is true for any odd index pair, as long as two words share the same multiset of even-indexed letters and the same multiset of odd-indexed letters, then they are special-equivalent. \n\nThat said, we can represent any multiset by the sorted even indexed letters concatenated with the sorted odd indexed letters:\n\n \'adcb\' and \'cdab\' represented by \'bd\' + \'ac\' = \'bdac\'\n\t\'abdc\' respresented by \'bc\' + \'ad\' = \'bcad\'\n\nEncode each word (using the method above) and add it to a set. The length of the set will then be equal the number of special equivalent families in A.\n\n### 5 Liner (for readability)\n\n```\nclass Solution:\n def numSpecialEquivGroups(self, A: List[str]) -> int:\n codes = set()\n for word in A:\n code = \'\'.join(sorted(word[::2])) + \'\'.join(sorted(word[1::2]))\n codes.add(code)\n return len(codes)\n```\n\n### One Liner\n\n```\nclass Solution:\n def numSpecialEquivGroups(self, A: List[str]) -> int:\n return len(set([\'\'.join(sorted(word[::2])) + \'\'.join(sorted(word[1::2])) for word in A]))\n```
3
0
[]
0
groups-of-special-equivalent-strings
Runtime 8 ms, C++ solution, using map
runtime-8-ms-c-solution-using-map-by-nip-0j18
\nclass Solution {\npublic:\n int numSpecialEquivGroups(vector<string>& A) {\n unordered_map<string, int> count;\n for(auto s : A)\n {\n
nipaafroz
NORMAL
2020-01-09T01:29:29.998635+00:00
2020-01-09T01:29:29.998696+00:00
186
false
```\nclass Solution {\npublic:\n int numSpecialEquivGroups(vector<string>& A) {\n unordered_map<string, int> count;\n for(auto s : A)\n {\n string even = "", odd = "";\n for(int i = 0; i < s.size(); i++)\n {\n if(i % 2 == 0)\n even += s[i];\n else odd += s[i];\n }\n sort(even.begin(), even.end());\n sort(odd.begin(), odd.end());\n string key = even + odd;\n count[key]++;\n }\n return count.size();\n }\n};\n```
3
0
[]
1
groups-of-special-equivalent-strings
Java 2ms Solution with HashSet with Explanation
java-2ms-solution-with-hashset-with-expl-onqd
/\nJava Solution Beat 100% runtime and 100% memory\n\nit is kind of anagram problem.\ntwo strings can only be Special-Equivalent when BOTH their odd letters AN
albeit2008
NORMAL
2019-09-08T15:00:20.295349+00:00
2019-09-08T15:08:31.515591+00:00
876
false
/*\nJava Solution Beat 100% runtime and 100% memory\n\nit is kind of anagram problem.\ntwo strings can only be Special-Equivalent when BOTH their odd letters AND even letters are anagrams.\n\nso based on above logic, \n1. we build hash value for each string, we sort odd position letters, even position letters of each string , since string is short, here only use simple O(n^2) compare logic to sort them.\n2. the odd and even sorted string will be the hash of the string.\n3. we add the hash into HashSet. (HashSet.add(value) will return true if it is added, and return falsle is already has the value in HashSet ), count how many values we added.\n4. return the count.\n*/\n\n```\nclass Solution {\n public int numSpecialEquivGroups(String[] A) {\n HashSet<String> set = new HashSet<>();\n int result = 0;\n for(String str: A){ \n if(set.add(getHashBySwap(str.toCharArray()))) {\n result++;\n }\n }\n return result;\n }\n \n private String getHashBySwap(char[] chars){\n for(int i=0; i<chars.length;i++){ \n for(int j=i+2;j<chars.length;){\n if(chars[i] > chars[j]) {\n char temp = chars[j];\n chars[j] = chars[i]; \n chars[i] = temp;\n }\n j+=2;\n }\n }\n \n return String.valueOf(chars); \n } \n\n}\n```
3
0
['Sorting', 'Java']
2
groups-of-special-equivalent-strings
Python Solution
python-solution-by-user1996a-m8a6
\n\ndef numSpecialEquivGroups(self, A):\n\t"""\n\t:type A: List[str]\n\t:rtype: int\n\t"""\n\tres = set()\n\tfor s in A:\n\t\ts = \'\'.join(sorted(s[::2]) + sor
user1996a
NORMAL
2019-07-27T22:21:02.728868+00:00
2019-07-27T22:21:02.728899+00:00
417
false
\n```\ndef numSpecialEquivGroups(self, A):\n\t"""\n\t:type A: List[str]\n\t:rtype: int\n\t"""\n\tres = set()\n\tfor s in A:\n\t\ts = \'\'.join(sorted(s[::2]) + sorted(s[1::2]))\n\t\tres.add(s)\n\treturn len(res)\n```
3
0
['Python3']
3
groups-of-special-equivalent-strings
my C++ solution
my-c-solution-by-tianboqiu-pwu0
s1 is the substring containing only characters on odd position\ns2 is the substring containing only characters on even position\nsort s1 and s2, use s1 + s2 as
tianboqiu
NORMAL
2018-11-12T15:15:18.784454+00:00
2018-11-12T15:15:18.784496+00:00
258
false
s1 is the substring containing only characters on odd position\ns2 is the substring containing only characters on even position\nsort s1 and s2, use s1 + s2 as the key of that string\ncompare the key of each string\n```\n#include <unordered_set>\n#include <algorithm>\nusing std::unordered_set;\nclass Solution {\npublic:\n string key(string s)\n {\n string s1 = "";\n string s2 = "";\n for(int i = 0; i < s.size(); i++)\n {\n if(i % 2)\n s1 += s[i];\n else\n s2 += s[i];\n }\n std::sort(s1.begin(),s1.end());\n std::sort(s2.begin(),s2.end());\n return s1 + s2;\n }\n int numSpecialEquivGroups(vector<string>& A) {\n unordered_set<string> sset;\n for(string s : A)\n sset.insert(key(s));\n return sset.size();\n \n }\n};\n```
3
0
[]
0
groups-of-special-equivalent-strings
BruteForce Java Solution using sort(O(m*nlogn))
bruteforce-java-solution-using-sortomnlo-smii
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n1. sort even and odd in
rajnarayansharma110
NORMAL
2024-10-19T13:04:12.132327+00:00
2024-10-19T13:04:12.132359+00:00
41
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. sort even and odd index seperate and put in a freq map\n2. hence more understandable approch\n# Complexity\n- Time complexity:O(m*nlogn)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(m*n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```java []\nclass Solution {\n public int numSpecialEquivGroups(String[] words) {\n Map<String, Integer> map = new HashMap<>();\n for (String s : words) {\n StringBuilder even = new StringBuilder();\n StringBuilder odd = new StringBuilder();\n for (int i = 0; i < s.length(); i++) {\n if (i % 2 == 0)\n even.append(s.charAt(i));\n else\n odd.append(s.charAt(i));\n }\n char[] evenArr = even.toString().toCharArray();\n char[] oddArr = odd.toString().toCharArray();\n Arrays.sort(evenArr);\n Arrays.sort(oddArr);\n String key = new String(evenArr) + new String(oddArr);\n map.merge(key, 1, Integer::sum);\n }\n return map.size();\n }\n}\n\n```
2
0
['Java']
0
groups-of-special-equivalent-strings
Solution
solution-by-deleted_user-az8b
C++ []\nclass Solution {\npublic:\n int numSpecialEquivGroups(vector<string>& words) {\n unordered_set<string> st;\n for (auto& w : words) {\n
deleted_user
NORMAL
2023-05-11T08:45:34.782420+00:00
2023-05-11T10:03:33.404536+00:00
359
false
```C++ []\nclass Solution {\npublic:\n int numSpecialEquivGroups(vector<string>& words) {\n unordered_set<string> st;\n for (auto& w : words) {\n string odd, even;\n for (int i = 0; i < w.size(); i++) {\n if (i % 2) even += w[i];\n else odd += w[i];\n }\n sort(even.begin(), even.end());\n sort(odd.begin(), odd.end());\n st.insert(even + odd);\n }\n return st.size();\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def numSpecialEquivGroups(self, A: List[str]) -> int:\n res = set()\n for s in A:\n sort_odd_even = \'\'.join(sorted(s[1::2]) + sorted(s[::2]))\n res.add(sort_odd_even)\n return len(res)\n```\n\n```Java []\nimport java.util.HashSet;\n\nclass Solution {\n public int numSpecialEquivGroups(String[] words) {\n HashSet<Integer> uniques = new HashSet<>();\n for (String word : words) uniques.add(customHash(word));\n return uniques.size();\n }\n private int customHash(String word) {\n int[] evenFreqs = new int[26], oddFreqs = new int[26];\n byte[] chars = word.getBytes();\n\n int n = chars.length;\n for (int i = 0, limit = n / 2 * 2; i < limit; i += 2) {\n ++evenFreqs[chars[i] - \'a\'];\n ++oddFreqs[chars[i + 1] - \'a\'];\n }\n if (n % 2 == 1) ++evenFreqs[chars[n - 1] - \'a\'];\n int acc = 0;\n for (int i = 0; i < 26; ++i) {\n acc = 31 * acc + evenFreqs[i];\n acc = 31 * acc + oddFreqs[i];\n }\n return acc;\n }\n}\n```\n
2
0
['C++', 'Java', 'Python3']
0
groups-of-special-equivalent-strings
Python Solution || run time 77%
python-solution-run-time-77-by-lalithkir-46vr
Code\n\nclass Solution(object):\n def numSpecialEquivGroups(self, words):\n """\n :type words: List[str]\n :rtype: int\n """\n
Lalithkiran
NORMAL
2023-02-25T04:28:42.740365+00:00
2023-02-25T04:28:42.740396+00:00
344
false
# Code\n```\nclass Solution(object):\n def numSpecialEquivGroups(self, words):\n """\n :type words: List[str]\n :rtype: int\n """\n lst=[]\n for i in words:\n evn=\'\'\n odd=\'\'\n for j in range(len(i)):\n if j%2==0:\n evn+=i[j]\n else:\n odd+=i[j]\n str=sorted(evn)+sorted(odd)\n lst.append("".join(str))\n return len(Counter(lst))\n```
2
0
['Python']
0
groups-of-special-equivalent-strings
c++ | solution using set | simple approach
c-solution-using-set-simple-approach-by-iwndd
\nclass Solution {\npublic:\n int numSpecialEquivGroups(vector<string>& words) {\n set<string>s; // declare set of strings\n for(auto i:word
utkarshb1209
NORMAL
2023-02-04T16:38:58.192462+00:00
2023-02-04T16:38:58.192497+00:00
288
false
```\nclass Solution {\npublic:\n int numSpecialEquivGroups(vector<string>& words) {\n set<string>s; // declare set of strings\n for(auto i:words){ \n string q="";\n string w="";\n for(int j=0;j<i.size();j++){\n if(j%2==0){\n q+=i[j]; // form a string of even indices \n }\n else {\n w+=i[j]; //form a string of odd indices \n }\n }\n sort(q.begin(),q.end()); // sort both strings separately\n sort(w.begin(),w.end());\n q+=w; // add them to form single string\n s.insert(q); // insert the added string to set \n }\n return s.size();\n }\n};\n```
2
0
['C', 'Ordered Set']
0
groups-of-special-equivalent-strings
Java 92% Time | 94% Memory Solution
java-92-time-94-memory-solution-by-tbekp-5nfg
Approach\n1. To define groups I need to find smth common between strings, which belong to one group. So, I create 2 arrays with size of 26 (alph -> alphabet). I
tbekpro
NORMAL
2022-12-20T06:28:52.989453+00:00
2022-12-20T06:28:52.989515+00:00
521
false
# Approach\n1. To define groups I need to find smth common between strings, which belong to one group. So, I create 2 arrays with size of 26 (alph -> alphabet). Inside findAlphabet() I go through evenly indexed letters and increment the relevant index in the first alph array. The same applied to letters with odd indices.\n2. Then I will use String as a key. For that I concatenate all numbers from both alph arrays. Then I use these strings to define uniqueness and put into the set.\n3. Finally, just return the size of that set.\n\nCheers! \n\n# Code\n```\nclass Solution {\n public int numSpecialEquivGroups(String[] words) {\n if (words.length == 1) return 1;\n Set<String> set = new HashSet<>();\n for (int i = 0; i < words.length; i++) {\n set.add(findAlphabet(words[i]));\n }\n return set.size();\n }\n\n private static String findAlphabet(String word) {\n byte[][] alph = new byte[2][26];\n for (int i = 0; i < word.length(); i+=2) {\n alph[0][word.charAt(i) - \'a\']++;\n }\n for (int i = 1; i < word.length(); i+=2) {\n alph[1][word.charAt(i) - \'a\']++;\n }\n StringBuilder sb = new StringBuilder();\n for (int i = 0; i < 26; i++) {\n sb.append(alph[0][i]);\n sb.append(alph[1][i]);\n }\n return sb.toString();\n }\n}\n```
2
0
['Java']
0
groups-of-special-equivalent-strings
C++ sol using set
c-sol-using-set-by-night_wolf-nbsr
class Solution {\npublic:\n int numSpecialEquivGroups(vector& words) {\n unordered_set s;\n for(const auto& w : words){\n string odd
night_wolf
NORMAL
2021-06-03T14:15:03.370112+00:00
2021-06-03T14:15:03.370158+00:00
114
false
class Solution {\npublic:\n int numSpecialEquivGroups(vector<string>& words) {\n unordered_set<string> s;\n for(const auto& w : words){\n string odd, even;\n for(int i=0;i<w.length();i++){\n \n if(i%2!=0) odd += w[i];\n even += w[i];}\n sort(even.begin(), even.end());\n sort(odd.begin(), odd.end());\n s.insert(even+odd);\n \n }\n return s.size();\n }\n};
2
0
[]
0
groups-of-special-equivalent-strings
Easy | Fast | Understandable | C++ Solution
easy-fast-understandable-c-solution-by-h-kjgk
UPVOTE IF THE SOLUTION MAKES SENSE TO YOU\n-> Solution to this problem as per this approach points to simple principle of dividing the string in to two parts -
hardy30894
NORMAL
2021-02-19T12:37:39.547657+00:00
2021-02-20T14:02:10.533778+00:00
219
false
UPVOTE IF THE SOLUTION MAKES SENSE TO YOU\n-> Solution to this problem as per this approach points to simple principle of dividing the string in to two parts - \n - One string with characters from odd indexes.\n - One string with characters from even indexes.\n \n Once we have these two individual parts, sort specific parts, combine them in to one and check for its existence in the hash map. If found increase frequency in hashmap else insert in hashmap.\n\n- Size of hashmap gives us the result to the problem.\n- -> Alternatively we can just use a set since we just need number of unique strings.\n```\nclass Solution {\npublic:\n int numSpecialEquivGroups(vector<string>& A) {\n int l = A.size();\n\t\tunordered_map<string, int> map; // initialize hashmap\n for(int i=0;i<l;i++){\n\t\t\tstring cur = A[i]; // take current string from array\n int slen = cur.length();\n string os = "";\n string es = "";\n for(int j=0;j<slen;j++){\n if(j%2==0){ // check index is even or odd\n os+=cur[j];\n }else{\n es+=cur[j];\n }\n }\n sort(os.begin(),os.end()); // sort by parts\n sort(es.begin(),es.end());\n cur = os+es;\n if(map.count(cur)>0){\n map[cur]+=1;\n }else{\n map[cur]=1;\n }\n }\n return map.size();\n }\n};\n```
2
0
['C']
0
groups-of-special-equivalent-strings
Python3 one liner solution faster than 69%
python3-one-liner-solution-faster-than-6-ixw2
\nclass Solution:\n def numSpecialEquivGroups(self, A: List[str]) -> int:\n return len({\'\'.join(sorted(a[::2]) + sorted(a[1::2])) for a in A})\n
mhviraf
NORMAL
2021-02-17T04:14:39.627459+00:00
2021-02-17T04:14:54.901787+00:00
464
false
```\nclass Solution:\n def numSpecialEquivGroups(self, A: List[str]) -> int:\n return len({\'\'.join(sorted(a[::2]) + sorted(a[1::2])) for a in A})\n```
2
0
['Python', 'Python3']
0
groups-of-special-equivalent-strings
C++ (4 ms) without sorting; beats 100% time 99% space
c-4-ms-without-sorting-beats-100-time-99-fjee
In this problem, it is understood that for a string if we maintain 2 hashsets for count of characters in odd and even places, and if both these hashsets match (
mihiraman
NORMAL
2020-07-03T08:41:57.344133+00:00
2020-07-03T08:47:12.042839+00:00
166
false
In this problem, it is understood that for a string if we maintain 2 hashsets for count of characters in odd and even places, and if both these hashsets match (corresponding) for 2 given strings, then both the strings can be grouped together i.e. are equivalent.\n\nBut to maintain a set of hashsets is a tedious job.\n\nSo to overcome that we maintain a unique identifier for these strings.( Example - we could have taken the sum of character values)\n\nBut then a simple sum wouldn\'t give us a unique identifier. Eg - \'abad\' and \'acac\' would map to same values i.e (0+0,1+3) = (0+0,2+2) i.e. (0,4)\n\nSo we look for a solution where sum of any 2 characters should not be equal to any other 2 characters.\n\nHence instead of labelling the characters from 0 to 25, we label them from 1 to 2^25.\n```\nint numSpecialEquivGroups(vector<string>& A) {\n set<pair<long long, long long>> s;\n int arr[26];\n arr[0] = 1;\n for(int i=1;i<26;i++)\n arr[i] = 2*arr[i-1];\n for(int i=0;i<A.size();i++)\n {\n long long a = 0;\n long long b = 0;\n for(int j=0;j<A[i].length();j++)\n {\n if(j%2==0)\n a += arr[A[i][j]-\'a\'];\n else\n b += arr[A[i][j]-\'a\'];\n }\n s.insert(make_pair(a,b));\n }\n return s.size();\n }\n```
2
0
[]
0
groups-of-special-equivalent-strings
Ruby solution. Represent word as array of 52 elements with 2 histograms in it.
ruby-solution-represent-word-as-array-of-a4wt
Leetcode: 893. Groups of Special-Equivalent Strings.\n\n\n\n##### Simplified approach.\n\nthnx @quantumlexa \n\nTwo strings are special equivalent if their his
user9697n
NORMAL
2020-06-23T16:29:27.418602+00:00
2020-06-23T16:50:28.888434+00:00
157
false
#### Leetcode: 893. Groups of Special-Equivalent Strings.\n\n\n\n##### Simplified approach.\n\n`thnx @quantumlexa` \n\nTwo strings are special equivalent if their histograms for even and odd indices are equal. Histogram for a word can be represented as 52 elments array, 26 for even 26 for odd symbols. Array mapped from array of words to array of histograms. Then make array contain only uniq values and return it\'s size.\n\nRuby code: \n```Ruby\n# Leetcode: 893. Groups of Special-Equivalent Strings.\n# https://leetcode.com/problems/groups-of-special-equivalent-strings/\n# thnx @quantumlexa\n# Runtime: 92 ms, faster than 10.00% of Ruby online submissions for Groups of Special-Equivalent Strings.\n# Memory Usage: 10.3 MB, less than 66.67% of Ruby online submissions for Groups of Special-Equivalent Strings.\n# @param {String[]} a\n# @return {Integer}\ndef num_special_equiv_groups(arr)\n arr.map!{|x|\n h = Array.new(52,0)\n (0...x.size).each do |i|\n h[26*(i%2) + x[i].ord - ?a.ord] += 1\n end\n h\n }.uniq.size\nend\n```\n\n##### Initial accepted approach.\n\nTwo strings are special equivalent if their histograms for even indexed chars and odd indexed chars are equal. Because there are only 26 different chars in this task, the both histograms could be represented as array of 52 elements. First map array of strings to array of histograms. Than create array name used to mark words that already in groups, and compare all words with each other by two loops external and internal one. External one iterates over all indexes, and internal start iteration from index after external one. Skip indexes already in groups for both arrays. When pointing on new index in external array if it is not used new group is started, during internal loop mark all words in this group as used. So on next iteration of external loop indices of this group will be skipped.\n\n\nRuby code:\n```Ruby\n# Leetcode: 893. Groups of Special-Equivalent Strings.\n# https://leetcode.com/problems/groups-of-special-equivalent-strings/\n# Runtime: 260 ms, faster than 10.00% of Ruby online submissions for Groups of Special-Equivalent Strings.\n# Memory Usage: 10.1 MB, less than 66.67% of Ruby online submissions for Groups of Special-Equivalent Strings.\n# @param {String[]} a\n# @return {Integer}\ndef num_special_equiv_groups(arr)\n arr.map!{|x|\n h = Array.new(52,0)\n (0...x.size).each do |i|\n h[26*(i%2) + x[i].ord - ?a.ord] += 1\n end\n h\n }\n groups = 0\n used = Array.new(arr.size,false)\n (0...arr.size).each do |i|\n next if used[i]\n used[i] = true\n groups += 1\n (i+1...arr.size).each do |j|\n next if used[j]\n used[j] = true if arr[i] == arr[j] \n end\n end\n groups\nend\n```
2
0
['Ruby']
1
groups-of-special-equivalent-strings
Easy Python Solution
easy-python-solution-by-ayu-99-fwf9
\nclass Solution:\n def numSpecialEquivGroups(self, A: List[str]) -> int:\n l=[]\n for s in A:\n even=""\n odd=""\n
ayu-99
NORMAL
2020-04-11T19:27:17.005304+00:00
2020-04-11T19:27:17.005333+00:00
244
false
```\nclass Solution:\n def numSpecialEquivGroups(self, A: List[str]) -> int:\n l=[]\n for s in A:\n even=""\n odd=""\n for i in range(len(s)):\n if i%2!=0:\n odd+=s[i]\n \n else:\n even+=s[i]\n \n odd = \'\'.join(sorted(odd))\n even = \'\'.join(sorted(even)) \n # odd=sorted(odd)\n # even=sorted(even)\n \n l.append(str(odd)+str(even))\n \n # print(l) \n \n return len(set(l)) \n```
2
0
['String', 'Python']
0
groups-of-special-equivalent-strings
[Python3] Group strings by sorting characters at even & odd indices
python3-group-strings-by-sorting-charact-513c
Algorithm:\nHere, we need a way to group strings so that each group is a special-equivalent group. Counting is one way as suggested by the Solution. Here, I\'ve
ye15
NORMAL
2020-02-17T22:42:16.893674+00:00
2020-02-17T22:42:16.893708+00:00
283
false
Algorithm:\nHere, we need a way to group strings so that each group is a special-equivalent group. Counting is one way as suggested by the Solution. Here, I\'ve used sorting-based approach. For a given string, sort the characters at even and odd indices respectively and join them. \n\n(36ms, 96.54%): \n```\nclass Solution:\n def numSpecialEquivGroups(self, A: List[str]) -> int:\n fn = lambda s: "".join(sorted(s[::2]) + sorted(s[1::2]))\n return len(set(fn(s) for s in A))\n```\n\nAnalysis:\nTime complexity `O(NlogN)`\nSpace complexity `O(N)`\n\nComment: Even though the time complexity is `O(NlogN)` in this approach, given `1 <= A[i].length <= 20`, it is still competative in terms of performance.
2
0
['Python3']
1
groups-of-special-equivalent-strings
Go 0ms map solution
go-0ms-map-solution-by-tjucoder-9lod
go\nfunc numSpecialEquivGroups(A []string) int {\n m := map[[52]int]interface{}{}\n for _, s := range A {\n array := [52]int{}\n for i, c :=
tjucoder
NORMAL
2020-02-14T14:53:28.782508+00:00
2020-02-14T14:53:28.782544+00:00
107
false
```go\nfunc numSpecialEquivGroups(A []string) int {\n m := map[[52]int]interface{}{}\n for _, s := range A {\n array := [52]int{}\n for i, c := range s {\n if i % 2 == 0 {\n array[c-\'a\']++\n } else {\n array[c-\'a\'+26]++\n }\n }\n m[array] = nil\n }\n return len(m)\n}\n```
2
0
['Go']
0
groups-of-special-equivalent-strings
java 4ms , customized hashing algorithm ,easy to understand
java-4ms-customized-hashing-algorithm-ea-kz59
customized a hashing algorithm that:\n1.split the string into 2 parts by index , the odd part and the even part\n2.count each char (a ~ z) in each part\n3.combi
powerrc
NORMAL
2019-05-09T22:36:10.798819+00:00
2019-05-09T22:36:10.798849+00:00
239
false
customized a hashing algorithm that:\n1.split the string into 2 parts by index , the odd part and the even part\n2.count each char (a ~ z) in each part\n3.combine the count result into a hashing string\n4.just add hashing string into a set\n5.return the size of this set\n```\nclass Solution {\n \n private String hash(String a){\n char[][] count = new char[2][26];\n \n Arrays.fill(count[0],\'a\');\n Arrays.fill(count[1],\'a\'); \n \n int index =0;\n \n for(char c : a.toCharArray()){\n count[index%2][c-\'a\']++;\n index++;\n }\n return (new String(count[0]))+"_"+(new String(count[1]));\n }\n \n public int numSpecialEquivGroups(String[] A) {\n HashSet<String> set = new HashSet<>();\n for(String aString: A){\n set.add(hash(aString));\n }\n return set.size();\n }\n}\n```
2
0
[]
1
groups-of-special-equivalent-strings
Python Easy to Understand 1-liner + other faster solution
python-easy-to-understand-1-liner-other-ky3ch
In the one liner, you just return the length of the set of tuples. Each tuple contain (sorted letters of even indexed letters, sorted letters of odd indexed let
rosemelon
NORMAL
2019-05-07T00:51:25.071738+00:00
2019-05-07T00:51:25.071782+00:00
242
false
In the one liner, you just return the length of the set of tuples. Each tuple contain (sorted letters of even indexed letters, sorted letters of odd indexed letters). This should be O(N*klogk), with k being the length of each word.\n\n`return len(set(tuple(sorted(word[::2])+sorted(word[1::2])) for word in A))`\n\nThis is the second solution, which is technically O(N*k), because each tup can only be length of 52, no matter how long k or N is. \n\nThey both run in 36 ms though, so a great example of when big O is not super helpful. \n\n```\nclass Solution(object):\n def numSpecialEquivGroups(self, A):\n """\n :type A: List[str]\n :rtype: int\n """\n uniqueSet = set()\n for word in A:\n tup = [0]*52\n for i in range(len(word)):\n tup[(ord(word[i])-ord(\'a\')) + 26*(i %2)] += 1 \n uniqueSet.add(tuple(tup))\n return len(uniqueSet)\n```
2
0
[]
0
groups-of-special-equivalent-strings
python3 one-liner
python3-one-liner-by-xdavidliu-tm9s
\n def numSpecialEquivGroups(self, A):\n return len({\'\'.join(sorted(word[::2]))+\'\'.join(sorted(word[1::2])) for word in A})\n\nuses letters at eve
xdavidliu
NORMAL
2018-11-08T02:42:03.396652+00:00
2018-11-08T02:42:03.396722+00:00
265
false
```\n def numSpecialEquivGroups(self, A):\n return len({\'\'.join(sorted(word[::2]))+\'\'.join(sorted(word[1::2])) for word in A})\n```\nuses letters at even positions, sorted, and letters at odd positions, also sorted, and combines them into a single string used as they key for a set, then returns the length of that set, e.g. the number of different unique keys. Each keys is a group.
2
0
[]
1
groups-of-special-equivalent-strings
Possible javascript solution with map and sort
possible-javascript-solution-with-map-an-ufx3
\nvar numSpecialEquivGroups = function(A) {\n var odd;\n var even;\n var key;\n var count = 0;\n var map = Object.create(null);\n for (var i =
eforce
NORMAL
2018-09-12T09:55:56.313120+00:00
2018-09-13T23:22:45.003322+00:00
252
false
```\nvar numSpecialEquivGroups = function(A) {\n var odd;\n var even;\n var key;\n var count = 0;\n var map = Object.create(null);\n for (var i = 0; i < A.length; i++) {\n odd = [];\n even = [];\n for (var j = 0; j < A[i].length; j++) {\n if (j % 2 === 0) {\n even.push(A[i][j]);\n } else {\n odd.push(A[i][j]);\n }\n }\n \n even.sort();\n odd.sort();\n \n key = even.join("") + odd.join("");\n if (!map[key]) {\n map[key] = true;\n count++;\n }\n }\n \n return count;\n};\n```
2
0
[]
0
groups-of-special-equivalent-strings
c++ solution beats 100%
c-solution-beats-100-by-hupodezhu-z3vj
class Solution {\npublic:\n int numSpecialEquivGroups(vector& A) {\n set s;\n \n for (auto &a : A) {\n string s1;\n
hupodezhu
NORMAL
2018-08-28T06:07:03.235420+00:00
2018-08-28T06:07:03.235462+00:00
299
false
class Solution {\npublic:\n int numSpecialEquivGroups(vector<string>& A) {\n set<string> s;\n \n for (auto &a : A) {\n string s1;\n string s2;\n for (int i = 0; i < a.size(); i++) {\n if (i % 2 == 0)\n s1 += a[i];\n else\n s2 += a[i];\n }\n sort(s1.begin(), s1.end());\n sort(s2.begin(), s2.end());\n s.insert(s1 + s2);\n }\n \n return s.size();\n }\n};
2
0
[]
1
groups-of-special-equivalent-strings
Python Straightforward Solution
python-straightforward-solution-by-zetru-xq4t
\nclass Solution(object):\n\tdef numSpecialEquivGroups(self, A):\n\t\t"""\n\t\t:type A: List[str]\n\t\t:rtype: int\n\t\t"""\n\t\tB = set()\n\t\tfor string in A:
zetrue_li
NORMAL
2018-08-26T07:03:16.137190+00:00
2018-09-06T05:28:10.939930+00:00
435
false
```\nclass Solution(object):\n\tdef numSpecialEquivGroups(self, A):\n\t\t"""\n\t\t:type A: List[str]\n\t\t:rtype: int\n\t\t"""\n\t\tB = set()\n\t\tfor string in A:\n\t\t\tC = list(string)\n\t\t\ta, b = C[::2], C[1::2]\n\t\t\tB.add((\'\'.join(sorted(a)), \'\'.join(sorted(b))))\n\t\t\t\n\t\treturn len(B)\n```
2
1
[]
4
groups-of-special-equivalent-strings
beats 100%
beats-100-by-giri_69-ypq5
IntuitionThe approach is same as : https://leetcode.com/problems/check-if-strings-can-be-made-equal-with-operations-ii/solutions/6381305/beats-100-c-by-giri_69-
giri_69
NORMAL
2025-02-05T17:54:36.947686+00:00
2025-02-05T17:54:36.947686+00:00
68
false
# Intuition The approach is same as : https://leetcode.com/problems/check-if-strings-can-be-made-equal-with-operations-ii/solutions/6381305/beats-100-c-by-giri_69-ld12/ The only diff is for grouping group the characters at even and odd index of strings together # Code ```cpp [] class Solution { public: int numSpecialEquivGroups(vector<string>& words) { unordered_set<string> uniqueGroups; for (auto &word : words) { string even = "", odd = ""; for (int j = 0; j < word.size(); j++) { if (j % 2 == 0) even += word[j]; else odd += word[j]; } sort(even.begin(), even.end()); sort(odd.begin(), odd.end()); string key = even + odd; uniqueGroups.insert(key); } return uniqueGroups.size(); } }; ```
1
0
['C++']
0
groups-of-special-equivalent-strings
Java brute force
java-brute-force-by-ihatealgothrim-m4p7
Intuition\nwords[i] and words[j]are special-equivalent means both have the same odd indexed chars, and even indexed chars\n\n# Approach\n- Each word, we can hav
IHateAlgothrim
NORMAL
2024-05-18T09:09:19.199669+00:00
2024-05-18T09:09:19.199697+00:00
167
false
# Intuition\n```words[i]``` and ```words[j]```are **special-equivalent** means both have the same odd indexed chars, and even indexed chars\n\n# Approach\n- Each word, we can have two temp storages, ```int[] odds = new int[26]```, and ```int[] evens = new int[26]```, which we can merge to ```int alphabet = new int[52]```, where first 26 items store all odd indexed chars, and last 26 items store all even indexed chars\n- Have a list to compare and store each unique ```alphabet``` using java built-in ```Arrays.equals``` function\n\n# Complexity\n- Time complexity: ```nonMatch``` gives O(n) in time complexity\nO(n^2)\n- Space complexity:\nO(n * 52)\n\n# Code\n```\nclass Solution {\n public int numSpecialEquivGroups(String[] words) {\n List<int[]> list = new ArrayList<>();\n\n for (String word : words) {\n int[] alphabet = new int[52];\n\n for (int i = 0; i < word.length(); i++) {\n int index = word.charAt(i) - \'a\' + (i % 2 == 0 ? 26 : 0);\n alphabet[index]++;\n }\n\n if (list.stream().noneMatch(alp -> Arrays.equals(alp, alphabet))) {\n list.add(alphabet);\n }\n }\n\n return list.size();\n }\n}\n```
1
0
['Java']
0
groups-of-special-equivalent-strings
100% beat
100-beat-by-somaycoder-7mm7
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
somaycoder
NORMAL
2024-04-17T21:13:02.198757+00:00
2024-04-17T21:13:02.198777+00:00
252
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 numSpecialEquivGroups(vector<string>& words) {\n int n = words.size();\n unordered_set<string>s;\n for(int i=0;i<n;i++){\n string even = "";\n string odd = "";\n string s1 = words[i];\n for(int i=0;i<s1.size();i++){\n if(i%2 == 0){\n even += s1[i];\n }\n else{\n odd += s1[i];\n }\n }\n sort(even.begin(),even.end());\n sort(odd.begin(),odd.end());\n string ans1 = even+odd;\n s.insert(ans1);\n }\n return s.size();\n }\n};\n```
1
0
['Array', 'Hash Table', 'Sorting', 'C++']
1
groups-of-special-equivalent-strings
Java Easy Solution
java-easy-solution-by-krishnachaubey2799-kqr1
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
krishnachaubey2799
NORMAL
2023-02-14T04:41:35.415535+00:00
2023-02-14T04:41:35.415581+00:00
418
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 numSpecialEquivGroups(String[] words) {\n HashSet<String> h=new HashSet<>();\n for(String str:words){\n int[] odd=new int[26];\n int [] even=new int[26];\n for(int i=0;i<str.length();i++){\n if(i%2==0){\n even[str.charAt(i)-\'a\']++;\n }else{\n odd[str.charAt(i)-\'a\']++;\n }}\n String key=Arrays.toString(odd)+Arrays.toString(even);\n h.add(key);\n \n }\n return h.size(); \n }\n}\n```
1
0
['Java']
0
groups-of-special-equivalent-strings
Pyton3 easy to understand solution
pyton3-easy-to-understand-solution-by-0i-r0ym
Approach\nSort the odd indices and even indices of the word seperately. Then combine those 2 to get the key value which is the same for special equivalent strin
0icy
NORMAL
2023-01-30T08:29:20.232591+00:00
2023-01-30T08:29:20.232637+00:00
449
false
# Approach\nSort the odd indices and even indices of the word seperately. Then combine those 2 to get the key value which is the same for special equivalent strings.\n\n\n\n# Code\n```\nfrom collections import defaultdict\nclass Solution:\n def numSpecialEquivGroups(self, words: List[str]) -> int:\n d = defaultdict(list)\n for word in words:\n odd , even = "",\'\'\n for idx,char in enumerate(word):\n if idx%2 == 0:\n even += char\n else:\n odd+= char\n\n odd = sorted(odd)\n even = sorted(even)\n final = "".join(odd+even)\n \n d[final].append(word)\n\n \n return len(d.values())\n```
1
0
['Python3']
0
groups-of-special-equivalent-strings
General Approach
general-approach-by-abhichauhan5682-2tz1
Intuition\nOdd index characters should be same and even index characters should be same for 2 different strings\n Describe your first thoughts on how to solve t
abhichauhan5682
NORMAL
2023-01-06T11:09:38.707855+00:00
2023-01-06T11:09:38.707895+00:00
99
false
# Intuition\nOdd index characters should be same and even index characters should be same for 2 different strings\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: O(n^2*(20+20log20)\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 int numSpecialEquivGroups(vector<string>& a) {\n int n=a.size();\n vector<bool>check(n,false);\n int ans=0;\n for(int i=0;i<n;i++){\n if(check[i]) continue;\n string odda="";\n string evena="";\n for(int k=0;k<a[i].size();k++){\n if(k%2) odda+=a[i][k];\n else evena+=a[i][k];\n }\n sort(begin(odda),end(odda));\n sort(begin(evena),end(evena));\n ans++;\n check[i]=true;\n for(int j=i+1;j<n;j++){\n if(check[j]) continue;\n string oddb="";\n string evenb="";\n for(int k=0;k<a[i].size();k++){\n if(k%2) oddb+=a[j][k];\n else evenb+=a[j][k];\n }\n sort(begin(oddb),end(oddb));\n sort(begin(evenb),end(evenb));\n if(odda==oddb&&evena==evenb){\n check[j]=true;\n }\n }\n }\n return ans;\n }\n};\n```
1
0
['C++']
0
groups-of-special-equivalent-strings
Solution, Runtime 16 ms, faster than 63.18% and Memory 8.8 MB, less than 68.16% of C++submissions
solution-runtime-16-ms-faster-than-6318-thv93
The idea is really very naive \uD83D\uDE05\uD83D\uDE05 .....the thought was if i create a unique key for a single group of equivalent strings\n\n-> Take even po
Indominous1
NORMAL
2022-10-30T16:46:56.853933+00:00
2022-11-17T19:15:24.524023+00:00
244
false
The idea is really very naive \uD83D\uDE05\uD83D\uDE05 .....the thought was if i create a unique key for a single group of equivalent strings\n\n-> Take even poisitioned characters and add them to form a string, then take odd poisitioned characters and add them to form a string.\n-> Now, sort both the strings as the question mentioned only odd poisitioned characters can be swapped with odd poistioned characters (same for even ones) if we sort them they must be equal\n->Append both the strings to form a key and put it into a map\n->Size of the map is our anwser\n```\nclass Solution {\npublic:\n int numSpecialEquivGroups(vector<string>& w) {\n map<string,int> mp;\n for(int i=0;i<w.size();i++)\n {\n string e="",o="",s=w[i];\n for(int j=0;j<s.size();j++)\n {\n if(j%2==0)\n e+=s[j];\n else\n o+=s[j];\n }\n sort(e.begin(),e.end());\n sort(o.begin(),o.end());\n mp[e+o]++;\n }\n return mp.size(); }\n};\n```
1
0
['Array', 'Hash Table', 'Math', 'C', 'C++']
0
groups-of-special-equivalent-strings
C++ easy solution using sets and hashmaps
c-easy-solution-using-sets-and-hashmaps-0ptia
\n\nclass Solution {\npublic:\n int numSpecialEquivGroups(vector& words) {\n int n=words.size();\n vector>v;\n \n for(auto it:wor
agarwalayush007
NORMAL
2022-08-27T17:04:46.195403+00:00
2022-08-27T17:04:46.195436+00:00
120
false
\n\nclass Solution {\npublic:\n int numSpecialEquivGroups(vector<string>& words) {\n int n=words.size();\n vector<pair<string,string>>v;\n \n for(auto it:words)\n {\n string even="";\n string odd="";\n for(int i=0;i<it.size();i+=2)even+=it[i];\n for(int i=1;i<it.size();i+=2)odd+=it[i];\n sort(even.begin(), even.end());\n sort(odd.begin(), odd.end());\n \n even+=odd;\n v.push_back({it,even});\n }\n \n map<string,int>m;\n for(auto it:v)\n m[it.second]++;\n \n for(auto it: m)\n cout<<it.first<<" ";\n \n return m.size();\n }\n \n};
1
0
['C', 'Ordered Set']
0
groups-of-special-equivalent-strings
Python O(n*m) HashMap 83.04%
python-onm-hashmap-8304-by-ya-anarka-uwju
\ndef numSpecialEquivGroups(self, words: List[str]) -> int:\n d = {}\n for word in words:\n even = [0] * 26\n odd = [0] * 26
ya-anarka
NORMAL
2022-08-27T05:33:13.508530+00:00
2022-08-27T05:35:52.166886+00:00
219
false
```\ndef numSpecialEquivGroups(self, words: List[str]) -> int:\n d = {}\n for word in words:\n even = [0] * 26\n odd = [0] * 26\n for i, c in enumerate(word):\n if i % 2 == 0:\n even[ord(c) - ord(\'a\')] += 1\n else:\n odd[ord(c) - ord(\'a\')] += 1\n hsh = tuple(even) + tuple(odd)\n if hsh not in d:\n d[hsh] = set()\n d[hsh].add(word)\n return len(d)\n```
1
0
['Counting Sort', 'Python']
0
groups-of-special-equivalent-strings
Python, 1 line
python-1-line-by-kingseaview-za9k
\nreturn len(Counter(\'\'.join(sorted(w[::2])+sorted(w[1::2])) for w in words))\n
kingseaview
NORMAL
2022-08-16T15:11:41.190344+00:00
2022-08-16T15:11:41.190375+00:00
199
false
```\nreturn len(Counter(\'\'.join(sorted(w[::2])+sorted(w[1::2])) for w in words))\n```
1
0
[]
0
groups-of-special-equivalent-strings
A sort and simple solution in C++
a-sort-and-simple-solution-in-c-by-rvraj-lgwd
```\n\t\t\n int numSpecialEquivGroups(vector& words) {\n \n set s;\n \n for(int i=0;i<words.size();i++){\n \n
Rvraj
NORMAL
2022-04-09T05:33:13.163432+00:00
2022-04-09T05:34:46.783303+00:00
73
false
```\n\t\t\n int numSpecialEquivGroups(vector<string>& words) {\n \n set<string> s;\n \n for(int i=0;i<words.size();i++){\n \n string st = words[i];\n string odd = "";\n string even = "";\n \n for(int j=0;j<st.size();j++){\n if(j%2==0)\n even=even+st[j];\n else\n odd=odd+st[j];\n }\n \n sort(odd.begin(),odd.end());\n sort(even.begin(),even.end());\n string t=even+odd;\n s.insert(t);\n }\n return s.size();\n }
1
0
[]
0
groups-of-special-equivalent-strings
Easy C++ solution
easy-c-solution-by-imran2018wahid-0ry0
\nclass Solution {\npublic:\n // This function stores the character frequency of the odd and even positions of a string\n void filler(string &str,vector<i
imran2018wahid
NORMAL
2021-12-07T03:57:41.304981+00:00
2021-12-07T03:57:41.305009+00:00
130
false
```\nclass Solution {\npublic:\n // This function stores the character frequency of the odd and even positions of a string\n void filler(string &str,vector<int>&odd,vector<int>&even) {\n for(int i=0;i<str.length();i++) {\n if(i%2==0) {\n even[str[i]-\'a\']++;\n }\n else {\n odd[str[i]-\'a\']++;\n }\n }\n }\n int numSpecialEquivGroups(vector<string>& words) {\n int n=words.size();\n \n // set is for grouping the strings.\n // The first element of pair is odd frequency\n // The second element of pair is even frequency\n set<pair<vector<int>,vector<int>>>dict;\n \n // odd vector stores the frequency at the odd positions of all the strings \n vector<vector<int>>odd(n,vector<int>(26,0));\n \n // even vector stores the frequency at the even positions of all the strings \n vector<vector<int>>even(n,vector<int>(26,0));\n for(int i=0;i<words.size();i++) {\n // calculate the frequency\n filler(words[i],odd[i],even[i]);\n \n // group the string \n dict.insert({odd[i],even[i]});\n }\n \n // finally set size will the group size\n return dict.size();\n }\n};\n```\n***Please upvote if you have got any help from my code. Thank you.***
1
0
['C']
1
groups-of-special-equivalent-strings
JAVA || HashSet || very easy
java-hashset-very-easy-by-ayushx-jv8o
\n public int numSpecialEquivGroups(String[] words) {\n HashSet<String> record = new HashSet<>();\n for (String str: words) {\n int[]
ayushx
NORMAL
2021-08-19T16:49:45.992293+00:00
2021-08-19T16:49:45.992330+00:00
202
false
```\n public int numSpecialEquivGroups(String[] words) {\n HashSet<String> record = new HashSet<>();\n for (String str: words) {\n int[] even = new int[26];\n int[] odd = new int[26];\n for (int i = 0; i < str.length(); i++) {\n if (i % 2 == 0) {\n even[str.charAt(i) - \'a\']++;\n } else {\n odd[str.charAt(i) - \'a\']++;\n }\n }\n record.add(Arrays.toString(even) + Arrays.toString(odd));\n }\n \n return record.size();\n }\n```
1
0
['Java']
0
groups-of-special-equivalent-strings
Python3 | Hashset
python3-hashset-by-swapnilsingh421-s9hv
TIME COMPLEXITY - O ( n * len ( word[ i ] ) )\nSPACE COMPLEXITY - O(N) in worst case\n\nclass Solution:\n def numSpecialEquivGroups(self, words: List[str]) -
swapnilsingh421
NORMAL
2021-08-06T13:08:11.942927+00:00
2021-08-06T13:08:11.942955+00:00
174
false
TIME COMPLEXITY - O ( n * len ( word[ i ] ) )\nSPACE COMPLEXITY - O(N) in worst case\n```\nclass Solution:\n def numSpecialEquivGroups(self, words: List[str]) -> int:\n hset=set()\n for i in range(len(words)):\n even=[0]*26\n odd=[0]*26\n for j in range(len(words[i])):\n if j%2==0:\n even[ord(words[i][j])-ord(\'a\')]+=1\n else:\n odd[ord(words[i][j])-ord(\'a\')]+=1\n hset.add("".join([str(even[i]) for i in range(len(even))])+"".join([str(odd[i]) for i in range(len(odd))]))\n return len(hset)\n```
1
0
['Python3']
0
groups-of-special-equivalent-strings
Java | Straight forward with explanation and example
java-straight-forward-with-explanation-a-f9li
\nQuestion is super convoluted. You just want the max number of string pair where if you can switch any even index char and/or odd index char, they match.\n\nUs
ssong716
NORMAL
2021-07-29T02:13:50.848603+00:00
2021-07-29T02:13:50.848639+00:00
92
false
\nQuestion is super convoluted. You just want the max number of string pair where if you can switch any even index char and/or odd index char, they match.\n\nUsing the given example, this is the mental mapping you want: \n```\n["abcd","cdab","cbad","xyzz","zzxy","zzyx"]\nabcd -> ac | bd\ncbad -> ac | bd\nxyzz -> xz | yz\nzzxy -> xz | yz\nzzyz -> yz | xz\n```\n\nApproach:\n1. for each string, group the characters in the even index\n2. group the characters in the odd index\n3. sort the group from step 1 and 2\n4. combine the sorted values from 3 `(e.g. (sorted chars from 1) | (sorted chars from 2)`\n5. use a map to count the groups you encountered, and increment by 1\n\n```\nclass Solution {\n public int numSpecialEquivGroups(String[] words) {\n Map<String, Integer> map = new HashMap<>();\n \n for (int i = 0; i < words.length; i++) {\n \n StringBuilder odd = new StringBuilder();\n StringBuilder even = new StringBuilder();\n \n String word = words[i];\n for (int j = 0; j < word.length(); j++) {\n if (j % 2 == 0) even.append(word.charAt(j));\n else odd.append(word.charAt(j));\n }\n StringBuilder sb = new StringBuilder();\n sb.append(sortString(odd.toString()));\n sb.append(sortString(even.toString()));\n map.put(sb.toString(), map.getOrDefault(sb.toString(), 0));\n }\n \n return map.size();\n }\n \n private String sortString(String str) {\n char[] chars = str.toCharArray();\n Arrays.sort(chars);\n return new String(chars);\n }\n}\n```
1
0
[]
0
groups-of-special-equivalent-strings
C++: Very easy to understand solution
c-very-easy-to-understand-solution-by-ra-5uyy
\nclass Solution {\npublic:\n int numSpecialEquivGroups(vector<string>& words) {\n unordered_map<string, bool> umap;\n int ans = 0;\n fo
rani_here_121
NORMAL
2021-07-27T12:49:34.877551+00:00
2021-07-27T12:49:34.877581+00:00
87
false
```\nclass Solution {\npublic:\n int numSpecialEquivGroups(vector<string>& words) {\n unordered_map<string, bool> umap;\n int ans = 0;\n for(int i=0; i<words.size(); i++){\n string odd = "";\n string even = "";\n for(int j=0; j<words[i].length(); j++){\n if(j%2) odd += words[i][j];\n else even += words[i][j];\n }\n sort(odd.begin(), odd.end());\n sort(even.begin(), even.end());\n string s = odd + even;\n if(umap[s] == 0){\n umap[s] = 1;\n ans++;\n }\n }\n return ans;\n }\n};\n```
1
0
[]
0
groups-of-special-equivalent-strings
Java | 90% faster
java-90-faster-by-shashank_tiwari1801-ffaq
\nclass Solution {\n String sortString(String str) {\n char []arr = str.toCharArray();\n Arrays.sort(arr);\n return (String.valueOf(arr)
Shashank_Tiwari1801
NORMAL
2021-07-04T13:19:51.520574+00:00
2021-07-04T13:19:51.520610+00:00
87
false
```\nclass Solution {\n String sortString(String str) {\n char []arr = str.toCharArray();\n Arrays.sort(arr);\n return (String.valueOf(arr));\n }\n public int numSpecialEquivGroups(String[] words) {\n HashSet<String> set = new HashSet<>();\n for(String s:words){\n StringBuilder curr = new StringBuilder();\n StringBuilder sb = new StringBuilder();\n for(int i=0;i<s.length();i+=2){\n sb.append(s.charAt(i));\n }\n curr.append(sortString(sb.toString()));\n sb = new StringBuilder();\n for(int i=1;i<s.length();i+=2){\n sb.append(s.charAt(i));\n }\n curr.append(sortString(sb.toString()));\n set.add(curr.toString());\n }\n return set.size();\n }\n}\n```
1
0
[]
0
groups-of-special-equivalent-strings
Poor description
poor-description-by-yashoda_agrawal-eiq8
This question has a simple solution. but it took alot of time to just understand the question\n\n\nclass Solution {\n public int numSpecialEquivGroups(String
yashoda_agrawal
NORMAL
2021-07-02T21:47:22.570120+00:00
2021-07-02T21:49:11.212863+00:00
62
false
This question has a simple solution. but it took alot of time to just understand the question\n\n```\nclass Solution {\n public int numSpecialEquivGroups(String[] words) {\n int len=words[0].length();\n int max=0;\n Map<String, Integer> map=new HashMap();\n for(String s:words)\n {\n StringBuilder sb=new StringBuilder();\n for(int i=0;i<len;i+=2)\n {\n sb.append(s.charAt(i));\n }\n char[] c=sb.toString().toCharArray();\n StringBuilder sb1=new StringBuilder();\n for(int i=1;i<len;i+=2)\n {\n sb1.append(s.charAt(i));\n \n }\n char[] b=sb1.toString().toCharArray();\n Arrays.sort(c);\n Arrays.sort(b);\n String temp=new String(b)+"#"+new String(c);\n map.put(temp,map.getOrDefault(temp,0)+1);\n max=Math.max(max,map.get(temp));\n }\n return map.size();\n }\n}\n```
1
0
[]
0
groups-of-special-equivalent-strings
c++ simple , aesy to understand solution
c-simple-aesy-to-understand-solution-by-3exru
\nclass Solution {\npublic:\n int numSpecialEquivGroups(vector<string>& words) {\n int i=0,n=words.size();\n vector<vector<string>> res;\n\n while(i
shubham7737
NORMAL
2021-06-20T09:31:25.545359+00:00
2021-06-20T09:31:25.545400+00:00
102
false
```\nclass Solution {\npublic:\n int numSpecialEquivGroups(vector<string>& words) {\n int i=0,n=words.size();\n vector<vector<string>> res;\n\n while(i<n){\n int j=0,m=words[i].length();\n string strt=words[i],t1="",t2="";\n while(j<m){\n\n if(j%2==0){\n t1+=strt[j];\n }else{\n t2+=strt[j];\n }\n j++;\n }\n sort(t1.begin(),t1.end());\n sort(t2.begin(),t2.end());\n vector<string> temp;\n temp.push_back(t1);\n temp.push_back(t2);\n res.push_back(temp);\n temp.clear();\n i++;\n }\n \n i=0;\n sort(res.begin(),res.end());\n \n i=0;\n int r=0;\n while(i<n){\n vector<string> t=res[i];\n i++;\n while(i<n && res[i]==t){\n i++;\n }\n cout<<" yes "<<i;\n r++;\n\n }\n return r;\n\n}\n};\n```
1
0
[]
0
groups-of-special-equivalent-strings
C++ 4ms (sorting)
c-4ms-sorting-by-wondertx-x1ts
\nclass Solution {\npublic:\n int numSpecialEquivGroups(std::vector<std::string>& words) {\n std::set<std::string> normed;\n for (auto && word : words) {
wondertx
NORMAL
2021-06-15T11:14:23.145453+00:00
2021-06-15T11:14:23.145499+00:00
98
false
```\nclass Solution {\npublic:\n int numSpecialEquivGroups(std::vector<std::string>& words) {\n std::set<std::string> normed;\n for (auto && word : words) {\n sortStr(word);\n normed.insert(word);\n }\n return normed.size();\n }\n\n void sortStr(std::string& word) {\n using std::swap;\n for (int i = 0; i < word.size(); i += 2) {\n for (int j = i + 2; j < word.size(); j += 2) {\n if (!(word[i] < word[j])) {\n swap(word[i], word[j]);\n }\n }\n }\n for (int i = 1; i < word.size(); i += 2) {\n for (int j = i + 2; j < word.size(); j += 2) {\n if (word[i] < word[j]) {\n swap(word[i], word[j]);\n }\n }\n }\n }\n};\n```
1
0
[]
0
groups-of-special-equivalent-strings
[with explanation] Python 40 ms faster than 80% and easy solution and one liner as well
with-explanation-python-40-ms-faster-tha-dey7
\nclass Solution:\n def numSpecialEquivGroups(self, words: List[str]) -> int:\n result = set()\n for i in words:\n i = \'\'.join(sor
alimlalani
NORMAL
2021-06-12T03:30:17.425975+00:00
2021-06-12T03:33:35.146154+00:00
85
false
```\nclass Solution:\n def numSpecialEquivGroups(self, words: List[str]) -> int:\n result = set()\n for i in words:\n i = \'\'.join(sorted(i[::2]) + sorted(i[1::2]))\n result.add(i)\n return (len(result))\n\n```\n\'\'\'\t\t\nThe list indices which we have used ([::2]) and ([1::2]) ,\nthis will give us odd and even elements respectively . \nAnd as we have declared result = set() when we add result.add(i), \nthe same elements won\'t repeat and we will get the len. \n\n you can also use set at the return statement, however you are comfortable with. \n Thank you please upvote if it helped :) \n \'\'\'\n```\nclass Solution:\n def numSpecialEquivGroups(self, words: List[str]) -> int:\n return len(set(\'\'.join(sorted(s[0::2]))+\'\'.join(sorted(s[1::2])) for s in words))\n\t\t\n
1
0
[]
0
groups-of-special-equivalent-strings
Share two Java solutions
share-two-java-solutions-by-ly2015cntj-57zh
java\n// \u65B9\u6CD5\u4E8C\uFF1A\u5F97\u5230\u6BCF\u4E2A\u5B57\u7B26\u4E32\u7684\u5947\u6570\u4F4D\u548C\u5076\u6570\u4F4D\u7EDF\u8BA1\u60C5\u51B5\u4EE5\u540E\
ly2015cntj
NORMAL
2021-05-18T14:12:46.282562+00:00
2021-05-18T14:12:46.282606+00:00
230
false
```java\n// \u65B9\u6CD5\u4E8C\uFF1A\u5F97\u5230\u6BCF\u4E2A\u5B57\u7B26\u4E32\u7684\u5947\u6570\u4F4D\u548C\u5076\u6570\u4F4D\u7EDF\u8BA1\u60C5\u51B5\u4EE5\u540E\uFF0C\u7EC4\u6210\u4E00\u4E2A\u7279\u5F81\u5B57\u7B26\u4E32\u5B58\u5165 set\uFF0C\u7528 set \u53BB\u91CD\n// AC: Runtime: 13 ms, faster than 55.72% of Java online submissions for Groups of Special-Equivalent Strings.\n// Memory Usage: 38.7 MB, less than 80.98% of Java online submissions for Groups of Special-Equivalent Strings.\n// \u7565\n// T:O(words.length * len(words[i])), S:O(words.length * len(words[i]))\n//\nclass Solution {\n public int numSpecialEquivGroups(String[] words) {\n HashSet<String> record = new HashSet<>();\n for (String str: words) {\n int[] even = new int[26];\n int[] odd = new int[26];\n for (int i = 0; i < str.length(); i++) {\n if (i % 2 == 0) {\n even[str.charAt(i) - \'a\']++;\n } else {\n odd[str.charAt(i) - \'a\']++;\n }\n }\n record.add(Arrays.toString(even) + Arrays.toString(odd));\n }\n \n return record.size();\n }\n}\n\n// \u65B9\u6CD5\u4E00\uFF1A\u76F4\u63A5\u904D\u5386\uFF0C\u9010\u4E2A\u5224\u65AD\u4E24\u4E24\u5B57\u7B26\u4E32\u662F\u5426\u5947\u6570\u4F4D\u548C\u5076\u6570\u4F4D\u7EC4\u6210\u76F8\u540C\u3002\n// AC: Runtime: 672 ms, faster than 5.05% of Java online submissions for Groups of Special-Equivalent Strings.\n// Memory Usage: 39.8 MB, less than 6.57% of Java online submissions for Groups of Special-Equivalent Strings.\n// T:O(words.length ^ 2 * len(words[i])), S:O(words.length * len(words[i]))\n// \nclass Solution {\n public int numSpecialEquivGroups(String[] words) {\n int size = words.length;\n List<HashSet<String>> record = new LinkedList<>();\n HashSet<Integer> used = new HashSet<>();\n for (int i = 0; i < size; i++) {\n if (used.contains(i)) {\n continue;\n }\n HashSet<String> temp = new HashSet<>();\n temp.add(words[i]);\n for (int j = i + 1; j < size; j++) {\n if (check(words[i], words[j])) {\n temp.add(words[j]);\n used.add(j);\n }\n }\n record.add(temp);\n }\n\n return record.size();\n }\n\n private boolean check(String s1, String s2) {\n HashMap<Character, Integer> even1 = new HashMap<>();\n HashMap<Character, Integer> even2 = new HashMap<>();\n HashMap<Character, Integer> odd1 = new HashMap<>();\n HashMap<Character, Integer> odd2 = new HashMap<>();\n for (int i = 0; i < s1.length(); i++) {\n if (i % 2 == 0) {\n even1.merge(s1.charAt(i), 1, Integer::sum);\n even2.merge(s2.charAt(i), 1, Integer::sum);\n } else {\n odd1.merge(s1.charAt(i), 1, Integer::sum);\n odd2.merge(s2.charAt(i), 1, Integer::sum);\n }\n }\n for (char c: even1.keySet()) {\n if (even2.get(c) == null || even1.get(c).intValue() != even2.get(c).intValue()) {\n return false;\n }\n }\n for (char c: odd1.keySet()) {\n if (odd2.get(c) == null || odd1.get(c).intValue() != odd2.get(c).intValue()) {\n return false;\n }\n }\n return true;\n }\n}\n\n\n```
1
0
['Java']
0
groups-of-special-equivalent-strings
java
java-by-190030070-vj1u
class Solution {\n public static int numSpecialEquivGroups(String[] A) {\n Set set = new HashSet<>();\n\n for (String s : A) {\n int
190030070
NORMAL
2021-03-18T06:13:37.637687+00:00
2021-03-18T06:13:37.637718+00:00
130
false
class Solution {\n public static int numSpecialEquivGroups(String[] A) {\n Set<String> set = new HashSet<>();\n\n for (String s : A) {\n int[] even = new int[26];\n int[] odd = new int[26];\n\n for (int i=0; i<s.length(); i++) {\n if (i%2 == 0) {\n even[s.charAt(i) - \'a\']++;\n }\n else {\n odd[s.charAt(i) - \'a\']++;\n }\n }\n\n set.add(Arrays.toString(even) + "|" + Arrays.toString(odd));\n }\n\n return set.size();\n }\n}
1
0
[]
0
groups-of-special-equivalent-strings
C++ solution
c-solution-by-oleksam-qr9b
\nint numSpecialEquivGroups(vector<string>& A) {\n\tset<string> sWords;\n\tfor (string w : A) {\n\t\tstring even = "", odd = "";\n\t\tfor (int i = 0; i < w.size
oleksam
NORMAL
2021-01-29T21:03:08.661930+00:00
2021-01-29T21:07:49.318054+00:00
169
false
```\nint numSpecialEquivGroups(vector<string>& A) {\n\tset<string> sWords;\n\tfor (string w : A) {\n\t\tstring even = "", odd = "";\n\t\tfor (int i = 0; i < w.size(); i += 2) {\n\t\t\teven += w[i];\n\t\t\todd += w[i + 1];\n\t\t}\n\t\tsort(begin(even), end(even));\n\t\tsort(begin(odd), end(odd));\n\t\tw = even + odd;\n\t\tsWords.insert(w);\n\t}\n\treturn sWords.size();\n}\n```
1
0
['C', 'C++']
0
groups-of-special-equivalent-strings
1 liner Python solution
1-liner-python-solution-by-faceplant-y8rf
\nreturn len({("".join(sorted(list(s[::2]))), "".join(sorted(list(s[1::2])))) for s in A})\n
FACEPLANT
NORMAL
2021-01-17T15:50:34.445480+00:00
2021-01-17T15:50:34.445522+00:00
152
false
```\nreturn len({("".join(sorted(list(s[::2]))), "".join(sorted(list(s[1::2])))) for s in A})\n```
1
1
[]
0
groups-of-special-equivalent-strings
C++|| 100% fast, simple solution
c-100-fast-simple-solution-by-know_go-5f5u
\nclass Solution{\n public:\n int numSpecialEquivGroups(vector<string>& A) {\n //00 sort the letter in strings in A:\n for(auto& word : A) {
know_go
NORMAL
2020-12-29T14:38:23.003323+00:00
2020-12-29T14:38:23.003407+00:00
120
false
```\nclass Solution{\n public:\n int numSpecialEquivGroups(vector<string>& A) {\n //00 sort the letter in strings in A:\n for(auto& word : A) {\n string s1, s2;\n for(int i = 0; i < word.size(); i += 2) {\n s1 += word[i];\n s2 += word[i + 1];\n }\n sort(s1.begin(), s1.end());\n sort(s2.begin(), s2.end());\n word = s1 + s2;\n }\n //01 sort the strings in A:\n sort(A.begin(), A.end());\n //02 count the group of strings:\n int cnt = 1;\n string temp = A[0];\n for(int i = 1; i < A.size(); ++i) {\n if(temp != A[i]) {\n ++cnt;\n temp = A[i];\n }\n }\n return cnt;\n }\n};\n```
1
0
[]
1
groups-of-special-equivalent-strings
C++ straightforward solution
c-straightforward-solution-by-nc-2mhw
\nclass Solution {\npublic:\n int numSpecialEquivGroups(vector<string>& A) {\n unordered_set<string> groups;\n \n for (auto& s: A) {\n
nc_
NORMAL
2020-12-14T06:33:16.419271+00:00
2020-12-14T06:33:16.419303+00:00
98
false
```\nclass Solution {\npublic:\n int numSpecialEquivGroups(vector<string>& A) {\n unordered_set<string> groups;\n \n for (auto& s: A) {\n string odd, even;\n for (int i = 0; i < s.size(); ++i)\n if (i%2)\n odd.push_back(s[i]);\n else\n even.push_back(s[i]);\n \n sort(odd.begin(), odd.end());\n sort(even.begin(), even.end());\n groups.insert(odd + even);\n }\n \n return groups.size();\n }\n};\n```
1
0
[]
0