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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116
11117
11118
11119
11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145
11146
11147
11148
11149
11150
11151
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
11175
11176
11177
11178
11179
11180
11181
11182
11183
11184
11185
11186
11187
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
11198
11199
11200
11201
11202
11203
11204
11205
11206
11207
11208
11209
11210
11211
11212
11213
11214
11215
11216
11217
11218
11219
11220
11221
11222
11223
11224
11225
11226
11227
11228
11229
11230
11231
11232
11233
11234
11235
11236
11237
11238
11239
11240
11241
11242
11243
11244
11245
11246
11247
11248
11249
11250
11251
11252
11253
11254
11255
11256
11257
11258
11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
11273
11274
11275
11276
11277
11278
11279
11280
11281
11282
11283
11284
11285
11286
11287
11288
11289
11290
11291
11292
11293
11294
11295
11296
11297
11298
11299
11300
11301
11302
11303
11304
11305
11306
11307
11308
11309
11310
11311
11312
11313
11314
11315
11316
11317
11318
11319
11320
11321
11322
11323
11324
11325
11326
11327
11328
11329
11330
11331
11332
11333
11334
11335
11336
11337
11338
11339
11340
11341
11342
11343
11344
11345
11346
11347
11348
11349
11350
11351
11352
11353
11354
11355
11356
11357
11358
11359
11360
11361
11362
11363
11364
11365
11366
11367
11368
11369
11370
11371
11372
11373
11374
11375
11376
11377
11378
11379
11380
11381
11382
11383
11384
11385
11386
11387
11388
11389
11390
11391
11392
11393
11394
11395
11396
11397
11398
11399
11400
11401
11402
11403
11404
11405
11406
11407
11408
11409
11410
11411
11412
11413
11414
11415
11416
11417
11418
11419
11420
11421
11422
11423
11424
11425
11426
11427
11428
11429
11430
11431
11432
11433
11434
11435
11436
11437
11438
11439
11440
11441
11442
11443
11444
11445
11446
11447
11448
11449
11450
11451
11452
11453
11454
11455
11456
11457
11458
11459
11460
11461
11462
11463
11464
11465
11466
11467
11468
11469
11470
11471
11472
11473
11474
11475
11476
11477
11478
11479
11480
11481
11482
11483
11484
11485
11486
11487
11488
11489
11490
11491
11492
11493
11494
11495
11496
11497
11498
11499
11500
11501
11502
11503
11504
11505
11506
11507
11508
11509
11510
11511
11512
11513
11514
11515
11516
11517
11518
11519
11520
11521
11522
11523
11524
11525
11526
11527
11528
11529
11530
11531
11532
11533
11534
11535
11536
11537
11538
11539
11540
11541
11542
11543
11544
11545
11546
11547
11548
11549
11550
11551
11552
11553
11554
11555
11556
11557
11558
11559
11560
11561
11562
11563
11564
11565
11566
11567
11568
11569
11570
11571
11572
11573
11574
11575
11576
11577
11578
11579
11580
11581
11582
11583
11584
11585
11586
11587
11588
11589
11590
11591
11592
11593
11594
11595
11596
11597
11598
11599
11600
11601
11602
11603
11604
11605
11606
11607
11608
11609
11610
11611
11612
11613
11614
11615
11616
11617
11618
11619
11620
11621
11622
11623
11624
11625
11626
11627
11628
11629
11630
11631
11632
11633
11634
11635
11636
11637
11638
11639
11640
11641
11642
11643
11644
11645
11646
11647
11648
11649
11650
11651
11652
11653
11654
11655
11656
11657
11658
11659
11660
11661
11662
11663
11664
11665
11666
11667
11668
11669
11670
11671
11672
11673
11674
11675
11676
11677
11678
11679
11680
11681
11682
11683
11684
11685
11686
11687
11688
11689
11690
11691
11692
11693
11694
11695
11696
11697
11698
11699
11700
11701
11702
11703
11704
11705
11706
11707
11708
11709
11710
11711
11712
11713
11714
11715
11716
11717
11718
11719
11720
11721
11722
11723
11724
11725
11726
11727
11728
11729
11730
11731
11732
11733
11734
11735
11736
11737
11738
11739
11740
11741
11742
11743
11744
11745
11746
11747
11748
11749
11750
11751
11752
11753
11754
11755
11756
11757
11758
11759
11760
11761
11762
11763
11764
11765
11766
11767
11768
11769
11770
11771
11772
11773
11774
11775
11776
11777
11778
11779
11780
11781
11782
11783
11784
11785
11786
11787
11788
11789
11790
11791
11792
11793
11794
11795
11796
11797
11798
11799
11800
11801
11802
11803
11804
11805
11806
11807
11808
11809
11810
11811
11812
11813
11814
11815
11816
11817
11818
11819
11820
11821
11822
11823
11824
11825
11826
11827
11828
11829
11830
11831
11832
11833
11834
11835
11836
11837
11838
11839
11840
11841
11842
11843
11844
11845
11846
11847
11848
11849
11850
11851
11852
11853
11854
11855
11856
11857
11858
11859
11860
11861
11862
11863
11864
11865
11866
11867
11868
11869
11870
11871
11872
11873
11874
11875
11876
11877
11878
11879
11880
11881
11882
11883
11884
11885
11886
11887
11888
11889
11890
11891
11892
11893
11894
11895
11896
11897
11898
11899
11900
11901
11902
11903
11904
11905
11906
11907
11908
11909
11910
11911
11912
11913
11914
11915
11916
11917
11918
11919
11920
11921
11922
11923
11924
11925
11926
11927
11928
11929
11930
11931
11932
11933
11934
11935
11936
11937
11938
11939
11940
11941
11942
11943
11944
11945
11946
11947
11948
11949
11950
11951
11952
11953
11954
11955
11956
11957
11958
11959
11960
11961
11962
11963
11964
11965
11966
11967
11968
11969
11970
11971
11972
11973
11974
11975
11976
11977
11978
11979
11980
11981
11982
11983
11984
11985
11986
11987
11988
11989
11990
11991
11992
11993
11994
11995
11996
11997
11998
11999
12000
12001
12002
12003
12004
12005
12006
12007
12008
12009
12010
12011
12012
12013
12014
12015
12016
12017
12018
12019
12020
12021
12022
12023
12024
12025
12026
12027
12028
12029
12030
12031
12032
12033
12034
12035
12036
12037
12038
12039
12040
12041
12042
12043
12044
12045
12046
12047
12048
12049
12050
12051
12052
12053
12054
12055
12056
12057
12058
12059
12060
12061
12062
12063
12064
12065
12066
12067
12068
12069
12070
12071
12072
12073
12074
12075
12076
12077
12078
12079
12080
12081
12082
12083
12084
12085
12086
12087
12088
12089
12090
12091
12092
12093
12094
12095
12096
12097
12098
12099
12100
12101
12102
12103
12104
12105
12106
12107
12108
12109
12110
12111
12112
12113
12114
12115
12116
12117
12118
12119
12120
12121
12122
12123
12124
12125
12126
12127
12128
12129
12130
12131
12132
12133
12134
12135
12136
12137
12138
12139
12140
12141
12142
12143
12144
12145
12146
12147
12148
12149
12150
12151
12152
12153
12154
12155
12156
12157
12158
12159
12160
12161
12162
12163
12164
12165
12166
12167
12168
12169
12170
12171
12172
12173
12174
12175
12176
12177
12178
12179
12180
12181
12182
12183
12184
12185
12186
12187
12188
12189
12190
12191
12192
12193
12194
12195
12196
12197
12198
12199
12200
12201
12202
12203
12204
12205
12206
12207
12208
12209
12210
12211
12212
12213
12214
12215
12216
12217
12218
12219
12220
12221
12222
12223
12224
12225
12226
12227
12228
12229
12230
12231
12232
12233
12234
12235
12236
12237
12238
12239
12240
12241
12242
12243
12244
12245
12246
12247
12248
12249
12250
12251
12252
12253
12254
12255
12256
12257
12258
12259
12260
12261
12262
12263
12264
12265
12266
12267
12268
12269
12270
12271
12272
12273
12274
12275
12276
12277
12278
12279
12280
12281
12282
12283
12284
12285
12286
12287
12288
12289
12290
12291
12292
12293
12294
12295
12296
12297
12298
12299
12300
12301
12302
12303
12304
12305
12306
12307
12308
12309
12310
12311
12312
12313
12314
12315
12316
12317
12318
12319
12320
12321
12322
12323
12324
12325
12326
12327
12328
12329
12330
12331
12332
12333
12334
12335
12336
12337
12338
12339
12340
12341
12342
12343
12344
12345
12346
12347
12348
12349
12350
12351
12352
12353
12354
12355
12356
12357
12358
12359
12360
12361
12362
12363
12364
12365
12366
12367
12368
12369
12370
12371
12372
12373
12374
12375
12376
12377
12378
12379
12380
12381
12382
12383
12384
12385
12386
12387
12388
12389
12390
12391
12392
12393
12394
12395
12396
12397
12398
12399
12400
12401
12402
12403
12404
12405
12406
12407
12408
12409
12410
12411
12412
12413
12414
12415
12416
12417
12418
12419
12420
12421
12422
12423
12424
12425
12426
12427
12428
12429
12430
12431
12432
12433
12434
12435
12436
12437
12438
12439
12440
12441
12442
12443
12444
12445
12446
12447
12448
12449
12450
12451
12452
12453
12454
12455
12456
12457
12458
12459
12460
12461
12462
12463
12464
12465
12466
12467
12468
12469
12470
12471
12472
12473
12474
12475
12476
12477
12478
12479
12480
12481
12482
12483
12484
12485
12486
12487
12488
12489
12490
12491
12492
12493
12494
12495
12496
12497
12498
12499
12500
12501
12502
12503
12504
12505
12506
12507
12508
12509
12510
12511
12512
12513
12514
12515
12516
12517
12518
12519
12520
12521
12522
12523
12524
12525
12526
12527
12528
12529
12530
12531
12532
12533
12534
12535
12536
12537
12538
12539
12540
12541
12542
12543
12544
12545
12546
12547
12548
12549
12550
12551
12552
12553
12554
12555
12556
12557
12558
12559
12560
12561
12562
12563
12564
12565
12566
12567
12568
12569
12570
12571
12572
12573
12574
12575
12576
12577
12578
12579
12580
12581
12582
12583
12584
12585
12586
12587
12588
12589
12590
12591
12592
12593
12594
12595
12596
12597
12598
12599
12600
12601
12602
12603
12604
12605
12606
12607
12608
12609
12610
12611
12612
12613
12614
12615
12616
12617
12618
12619
12620
12621
12622
12623
12624
12625
12626
12627
12628
12629
12630
12631
12632
12633
12634
12635
12636
12637
12638
12639
12640
12641
12642
12643
12644
12645
12646
12647
12648
12649
12650
12651
12652
12653
12654
12655
12656
12657
12658
12659
12660
12661
12662
12663
12664
12665
12666
12667
12668
12669
12670
12671
12672
12673
12674
12675
12676
12677
12678
12679
12680
12681
12682
12683
12684
12685
12686
12687
12688
12689
12690
12691
12692
12693
12694
12695
12696
12697
12698
12699
12700
12701
12702
12703
12704
12705
12706
12707
12708
12709
12710
12711
12712
12713
12714
12715
12716
12717
12718
12719
12720
12721
12722
12723
12724
12725
12726
12727
12728
12729
12730
12731
12732
12733
12734
12735
12736
12737
12738
12739
12740
12741
12742
12743
12744
12745
12746
12747
12748
12749
12750
12751
12752
12753
12754
12755
12756
12757
12758
12759
12760
12761
12762
12763
12764
12765
12766
12767
12768
12769
12770
12771
12772
12773
12774
12775
12776
12777
12778
12779
12780
12781
12782
12783
12784
12785
12786
12787
12788
12789
12790
12791
12792
12793
12794
12795
12796
12797
12798
12799
12800
12801
12802
12803
12804
12805
12806
12807
12808
12809
12810
12811
12812
12813
12814
12815
12816
12817
12818
12819
12820
12821
12822
12823
12824
12825
12826
12827
12828
12829
12830
12831
12832
12833
12834
12835
12836
12837
12838
12839
12840
12841
12842
12843
12844
12845
12846
12847
12848
12849
12850
12851
12852
12853
12854
12855
12856
12857
12858
12859
12860
12861
12862
12863
12864
12865
12866
12867
12868
12869
12870
12871
12872
12873
12874
12875
12876
12877
12878
12879
12880
12881
12882
12883
12884
12885
12886
12887
12888
12889
12890
12891
12892
12893
12894
12895
12896
12897
12898
12899
12900
12901
12902
12903
12904
12905
12906
12907
12908
12909
12910
12911
12912
12913
12914
12915
12916
12917
12918
12919
12920
12921
12922
12923
12924
12925
12926
12927
12928
12929
12930
12931
12932
12933
12934
12935
12936
12937
12938
12939
12940
12941
12942
12943
12944
12945
12946
12947
12948
12949
12950
12951
12952
12953
12954
12955
12956
12957
12958
12959
12960
12961
12962
12963
12964
12965
12966
12967
12968
12969
12970
12971
12972
12973
12974
12975
12976
12977
12978
12979
12980
12981
12982
12983
12984
12985
12986
12987
12988
12989
12990
12991
12992
12993
12994
12995
12996
12997
12998
12999
13000
13001
13002
13003
13004
13005
13006
13007
13008
13009
13010
13011
13012
13013
13014
13015
13016
13017
13018
13019
13020
13021
13022
13023
13024
13025
13026
13027
13028
13029
13030
13031
13032
13033
13034
13035
13036
13037
13038
13039
13040
13041
13042
13043
13044
13045
13046
13047
13048
13049
13050
13051
13052
13053
13054
13055
13056
13057
13058
13059
13060
13061
13062
13063
13064
13065
13066
13067
13068
13069
13070
13071
13072
13073
13074
13075
13076
13077
13078
13079
13080
13081
13082
13083
13084
13085
13086
13087
13088
13089
13090
13091
13092
13093
13094
13095
13096
13097
13098
13099
13100
13101
13102
13103
13104
13105
13106
13107
13108
13109
13110
13111
13112
13113
13114
13115
13116
13117
13118
13119
13120
13121
13122
13123
13124
13125
13126
13127
13128
13129
13130
13131
13132
13133
13134
13135
13136
13137
13138
13139
13140
13141
13142
13143
13144
13145
13146
13147
13148
13149
13150
13151
13152
13153
13154
13155
13156
13157
13158
13159
13160
13161
13162
13163
13164
13165
13166
13167
13168
13169
13170
13171
13172
13173
13174
13175
13176
13177
13178
13179
13180
13181
13182
13183
13184
13185
13186
13187
13188
13189
13190
13191
13192
13193
13194
13195
13196
13197
13198
13199
13200
13201
13202
13203
13204
13205
13206
13207
13208
13209
13210
13211
13212
13213
13214
13215
13216
13217
13218
13219
13220
13221
13222
13223
13224
13225
13226
13227
13228
13229
13230
13231
13232
13233
13234
13235
13236
13237
13238
13239
13240
13241
13242
13243
13244
13245
13246
13247
13248
13249
13250
13251
13252
13253
13254
13255
13256
13257
13258
13259
13260
13261
13262
13263
13264
13265
13266
13267
13268
13269
13270
13271
13272
13273
13274
13275
13276
13277
13278
13279
13280
13281
13282
13283
13284
13285
13286
13287
13288
13289
13290
13291
13292
13293
13294
13295
13296
13297
13298
13299
13300
13301
13302
13303
13304
13305
13306
13307
13308
13309
13310
13311
13312
13313
13314
13315
13316
13317
13318
13319
13320
13321
13322
13323
13324
13325
13326
13327
13328
13329
13330
13331
13332
13333
13334
13335
13336
13337
13338
13339
13340
13341
13342
13343
13344
13345
13346
13347
13348
13349
13350
13351
13352
13353
13354
13355
13356
13357
13358
13359
13360
13361
13362
13363
13364
13365
13366
13367
13368
13369
13370
13371
13372
13373
13374
13375
13376
13377
13378
13379
13380
13381
13382
13383
13384
13385
13386
13387
13388
13389
13390
13391
13392
13393
13394
13395
13396
13397
13398
13399
13400
13401
13402
13403
13404
13405
13406
13407
13408
13409
13410
13411
13412
13413
13414
13415
13416
13417
13418
13419
13420
13421
13422
13423
13424
13425
13426
13427
13428
13429
13430
13431
13432
13433
13434
13435
13436
13437
13438
13439
13440
13441
13442
13443
13444
13445
13446
13447
13448
13449
13450
13451
13452
13453
13454
13455
13456
13457
13458
13459
13460
13461
13462
13463
13464
13465
13466
13467
13468
13469
13470
13471
13472
13473
13474
13475
13476
13477
13478
13479
13480
13481
13482
13483
13484
13485
13486
13487
13488
13489
13490
13491
13492
13493
13494
13495
13496
13497
13498
13499
13500
13501
13502
13503
13504
13505
13506
13507
13508
13509
13510
13511
13512
13513
13514
13515
13516
13517
13518
13519
13520
13521
13522
13523
13524
13525
13526
13527
13528
13529
13530
13531
13532
13533
13534
13535
13536
13537
13538
13539
13540
13541
13542
13543
13544
13545
13546
13547
13548
13549
13550
13551
13552
13553
13554
13555
13556
13557
13558
13559
13560
13561
13562
13563
13564
13565
13566
13567
13568
13569
13570
13571
13572
13573
13574
13575
13576
13577
13578
13579
13580
13581
13582
13583
13584
13585
13586
13587
13588
13589
13590
13591
13592
13593
13594
13595
13596
13597
13598
13599
13600
13601
13602
13603
13604
13605
13606
13607
13608
13609
13610
13611
13612
13613
13614
13615
13616
13617
13618
13619
13620
13621
13622
13623
13624
13625
13626
13627
13628
13629
13630
13631
13632
13633
13634
13635
13636
13637
13638
13639
13640
13641
13642
13643
13644
13645
13646
13647
13648
13649
13650
13651
13652
13653
13654
13655
13656
13657
13658
13659
13660
13661
13662
13663
13664
13665
13666
13667
13668
13669
13670
13671
13672
13673
13674
13675
13676
13677
13678
13679
13680
13681
13682
13683
13684
13685
13686
13687
13688
13689
13690
13691
13692
13693
13694
13695
13696
13697
13698
13699
13700
13701
13702
13703
13704
13705
13706
13707
13708
13709
13710
13711
13712
13713
13714
13715
13716
13717
13718
13719
13720
13721
13722
13723
13724
13725
13726
13727
13728
13729
13730
13731
13732
13733
13734
13735
13736
13737
13738
13739
13740
13741
13742
13743
13744
13745
13746
13747
13748
13749
13750
13751
13752
13753
13754
13755
13756
13757
13758
13759
13760
13761
13762
13763
13764
13765
13766
13767
13768
13769
13770
13771
13772
13773
13774
13775
13776
13777
13778
13779
13780
13781
13782
13783
13784
13785
13786
13787
13788
13789
13790
13791
13792
13793
13794
13795
13796
13797
13798
13799
13800
13801
13802
13803
13804
13805
13806
13807
13808
13809
13810
13811
13812
13813
13814
13815
13816
13817
13818
13819
13820
13821
13822
13823
13824
13825
13826
13827
13828
13829
13830
13831
13832
13833
13834
13835
13836
13837
13838
13839
13840
13841
13842
13843
13844
13845
13846
13847
13848
13849
13850
13851
13852
13853
13854
13855
13856
13857
13858
13859
13860
13861
13862
13863
13864
13865
13866
13867
13868
13869
13870
13871
13872
13873
13874
13875
13876
13877
13878
13879
13880
13881
13882
13883
13884
13885
13886
13887
13888
13889
13890
13891
13892
13893
13894
13895
13896
13897
13898
13899
13900
13901
13902
13903
13904
Code_ID,Code_Text,"Label (0- HUMAN, 1-AI)",Source_Type,Generation_Prompt,Language
,"import requests  
from bs4 import BeautifulSoup 
from concurrent.futures import ThreadPoolExecutor  # Import ThreadPoolExecutor for multi-threading
import urllib.robotparser  
from urllib.parse import urlparse, urljoin  # Import urlparse and urljoin for URL manipulation


def is_allowed(url, user_agent='*'):

    parsed_url = urlparse(url)
    base_url = f'{parsed_url.scheme}://{parsed_url.netloc}'
    robots_url = urljoin(base_url, 'robots.txt')
    
    
    rp = urllib.robotparser.RobotFileParser()
    rp.set_url(robots_url)
    rp.read()
    
 
    return rp.can_fetch(user_agent, url)


def fetch_page(url):
    
    if not is_allowed(url):
        print(f'Scraping not allowed for {url}')
        return None
    
    try:
       
        response = requests.get(url)
        
        if response.status_code == 200:
            print(f'Successfully fetched {url}')
           
            soup = BeautifulSoup(response.content, 'html.parser')
            return soup
        else:
            print(f'Failed to fetch {url} with status code {response.status_code}')
    except Exception as e:
        print(f'Exception occurred while fetching {url}: {e}')
    return None


def extract_links(soup, base_url):
    links = []
    if soup:
      
        for link in soup.find_all('a', href=True):
           
            full_url = urljoin(base_url, link['href'])
            links.append(full_url)
    return links


def scrape_urls(urls, max_workers=5):
    with ThreadPoolExecutor(max_workers=max_workers) as executor:
       
        futures = {executor.submit(fetch_page, url): url for url in urls}
        results = []
        for future in futures:
            result = future.result()
            if result:
                results.append(result)
        return results


def main():
    start_url = 'https://example.com'  # Replace with the URL you want to start scraping from
    
    soup = fetch_page(start_url)
    if not soup:
        return
    
   
    links = extract_links(soup, start_url)
    
    pages = scrape_urls(links)
    
   
    for page in pages:
       
        if page:
            title = page.find('title').get_text()
            print(f'Page title: {title}')

if __name__ == '__main__':
    main()",0,W3RESOURCE,NA,PYTHON
,"import numpy as np

arr = np.random.randint(0, 10**6, size=10**7)

# For loop
def find_max(arr):
    m = arr[0]
    for num in arr:
        if num > m:
            m = num
    return m

print(""Max with loop:"", find_max(arr))
print(""Max with np.max:"", np.max(arr))",1,DEEPAI,Write a NumPy program to generate a large NumPy array and write a function to find the maximum element using a for loop. Optimize it using NumPy's built-in functions.,PYTHON
,"import time  # Import the time module to measure execution time

class LogExecutionTime:  # Define a class for the decorator
    def __init__(self, func):  # Initialize the decorator with the function to be decorated
        self.func = func  # Store the function to be decorated

    def __get__(self, instance, owner):  # Define the descriptor method to handle instance methods
        return lambda *args, **kwargs: self(instance, *args, **kwargs)  # Return a lambda that passes the instance

    def __call__(self, *args, **kwargs):  # Make the class instance callable
        instance = args[0]  # Extract the instance from the arguments
        start_time = time.time()  # Record the start time
        result = self.func(instance, *args[1:], **kwargs)  # Call the original function with its arguments
        end_time = time.time()  # Record the end time
        execution_time = end_time - start_time  # Calculate the execution time
        print(f""Execution time of {self.func.__name__}: {execution_time:.4f} seconds"")  # Log the execution time
        return result  # Return the result of the original function call

# Example usage:

class ExampleClass:  # Define an example class to demonstrate the decorator
    @LogExecutionTime  # Apply the decorator to the method
    def example_method(self):  # Define a method in the class
        for _ in range(1000000):  # A sample computation to add some delay
            pass  # Do nothing

# Instantiate the example class and call the decorated method
example = ExampleClass()  # Create an instance of the ExampleClass
example.example_method()  # Call the decorated method to see the execution time log",0,W3RESOURCE,NA,PYTHON
,"import numpy as np

# Example 2D array
arr = np.array([[3, 2, 5],
                [1, 4, 6],
                [2, 1, 7]])

n = 1  # The column index to sort by (0-based)

# Get the indices that would sort the array by column n
sorted_indices = np.argsort(arr[:, n])

# Sort the array by the specified column
sorted_arr = arr[sorted_indices]

print(""Array sorted by column"", n, "":\n"", sorted_arr)",1,DEEPAI,Write a NumPy program to sort an given array by the nth column.,PYTHON
,"# Define a function to perform matrix multiplication of matrices A and B
def matrix_multiplication(A, B):
    """"""
    Perform matrix multiplication of matrices A and B.

    Args:
    A: First matrix (list of lists).
    B: Second matrix (list of lists).

    Returns:
    Result of matrix multiplication (list of lists).
    """"""
    if len(A[0]) != len(B):
        raise ValueError(""Number of columns in A must equal number of rows in B"")

    # Number of rows and columns in resulting matrix
    num_rows_A = len(A)
    num_cols_B = len(B[0])

    # Perform matrix multiplication using list comprehension
    result = [[sum(A[i][k] * B[k][j] for k in range(len(B))) for j in range(num_cols_B)] for i in range(num_rows_A)]

    return result

# Example usage:
if __name__ == ""__main__"":
    # Example matrices A and B
    A = [[1, 2, 3],
         [4, 5, 6]]

    B = [[7, 8],
         [9, 10],
         [11, 12]]

    # Print the result of matrix multiplication
    print(matrix_multiplication(A, B))
Output:",0,W3RESOURCE,NA,PYTHON
,"import numpy as np

arr = np.array([9, 3, 5, 1, 8, 2, 7])
n = 4  # Number of elements to sort from the beginning

# Sort the first n elements
sorted_part = np.sort(arr[:n])

# Concatenate sorted part with the rest of the array
result = np.concatenate((sorted_part, arr[n:]))

print(""Array after sorting first"", n, ""elements:"", result)",1,DEEPAI,Write a NumPy program to sort the specified number of elements from beginning of a given array.,PYTHON
,"# Import the queue module to use PriorityQueue
import queue
# Import the threading module to use threads and locks
import threading

# Define a class for a thread-safe priority queue
class ThreadSafePriorityQueue:
    def __init__(self):
        # Initialize a PriorityQueue object to hold the items
        self._queue = queue.PriorityQueue()
        # Initialize a lock to ensure thread safety
        self._lock = threading.Lock()

    # Method to put an item into the priority queue
    def put(self, item, priority):
        # Acquire the lock to ensure thread safety
        with self._lock:
            # Put the item into the queue with its priority
            self._queue.put((priority, item))

    # Method to get an item from the priority queue
    def get(self):
        # Acquire the lock to ensure thread safety
        with self._lock:
            # Check if the queue is not empty
            if not self._queue.empty():
                # Get the item with the highest priority (lowest priority number)
                priority, item = self._queue.get()
                # Return the item
                return item
            else:
                # Return None if the queue is empty
                return None

# Example usage to demonstrate the thread-safe priority queue
if __name__ == ""__main__"":
    # Define a producer function to add items to the queue
    def producer(q):
        # Add 5 items to the queue with their priority as their value
        for i in range(5):
            q.put(i, i)

    # Define a consumer function to get items from the queue
    def consumer(q):
        # Continuously get items from the queue
        while True:
            # Get an item from the queue
            item = q.get()
            # If the item is None, break the loop (end of processing)
            if item is None:
                break
            # Print the consumed item
            print(""Consumed:"", item)

    # Create an instance of the thread-safe priority queue
    q = ThreadSafePriorityQueue()
    # Create a producer thread to add items to the queue
    producer_thread = threading.Thread(target=producer, args=(q,))
    # Create a consumer thread to get items from the queue
    consumer_thread = threading.Thread(target=consumer, args=(q,))

    # Start the producer thread
    producer_thread.start()
    # Start the consumer thread
    consumer_thread.start()

    # Wait for the producer thread to finish
    producer_thread.join()
    # Add a sentinel value to the queue to signal the consumer to stop
    q.put(None, None)
    # Wait for the consumer thread to finish
    consumer_thread.join()",0,W3RESOURCE,NA,PYTHON
,"import numpy as np

arr = np.array([9, 3, 5, 1, 8, 2, 7])
k = 3  # Partition index

partitioned_arr = np.partition(arr, k)
print(""Partitioned array:"", partitioned_arr)",1,DEEPAI,"Write a NumPy program to partition a given array in a specified position and move all the smaller elements values to the left of the partition, and the remaining values to the right, in arbitrary order (based on random choice)",PYTHON
,"import numpy as np

arr = np.array([3+4j, 1+7j, 3+2j, 2+5j, 1+2j])
# Use lexsort with imaginary part as the first key, real part as the second
sorted_indices = np.lexsort((np.imag(arr), np.real(arr)))
sorted_arr = arr[sorted_indices]

print(""Sorted array:"", sorted_arr)",1,DEEPAI,"Write a NumPy program to sort a given complex array using the real part first, then the imaginary part.",PYTHON
,"# Define a class representing a node in a tree
class TreeNode:
    def __init__(self, value):
        self.value = value
        self.children = []  # Initialize an empty list to store child nodes

    def add_child(self, child_node):
        self.children.append(child_node)  # Add a child node to the list of children

# Define a class implementing a custom iterator for tree traversal
class TreeIterator:
    def __init__(self, root):
        self.stack = [root]  # Initialize stack with root node

    def __iter__(self):
        return self

    def __next__(self):
        if not self.stack:  # If stack is empty, no more nodes to traverse
            raise StopIteration
        node = self.stack.pop()  # Get the top node from stack
        for child in reversed(node.children):  # Add children to stack in reverse order
            self.stack.append(child)
        return node.value

# Example usage:
if __name__ == ""__main__"":
    # Create a tree with a root node and some child nodes
    root = TreeNode(1)
    root.add_child(TreeNode(2))
    root.add_child(TreeNode(3))
    root.children[0].add_child(TreeNode(4))
    root.children[0].add_child(TreeNode(5))
    root.children[1].add_child(TreeNode(6))

    # Create a TreeIterator instance and iterate over the tree
    tree_iterator = TreeIterator(root)
    for value in tree_iterator:
        print(value)",0,W3RESOURCE,NA,PYTHON
,"import numpy as np

arr = np.array([4, 2, 9, 7, 1])
indices = np.argsort(arr)
print(""Indices of sorted elements:"", indices)",1,DEEPAI,Write a NumPy program to get the indices of the sorted elements of a given array.,PYTHON
,"# Import necessary modules
from dataclasses import dataclass, field, fields, Field
from typing import Any, Callable, List, get_type_hints

# Custom exception for validation errors
class ValidationError(Exception):
    pass

# Function to validate dataclass fields
def validate(instance):
    cls = instance.__class__
    hints = get_type_hints(cls)
    # Iterate through fields and type hints
    for name, type_hint in hints.items():
        value = getattr(instance, name)
        # Check if value matches type hint
        if not isinstance(value, type_hint):
            raise ValidationError(f""Field '{name}' expects {type_hint}, got {type(value)}"")
        # Check for custom validators
        field: Field = next(f for f in fields(cls) if f.name == name)
        if 'validators' in field.metadata:
            for validator in field.metadata['validators']:
                validator(instance, value)

# Decorator to define a validator function
def validator(func: Callable[[Any, Any], None]):
    if not callable(func):
        raise ValueError(""Validator must be callable"")
    func._is_validator = True
    return func

# Function to define a field with validation
def field_with_validation(*, default: Any = None, default_factory: Callable[[], Any] = None, validators: List[Callable[[Any, Any], None]] = None) -> Field:
    # Ensure only one of default or default_factory is provided
    if default is not None and default_factory is not None:
        raise ValueError('cannot specify both default and default_factory')
    
    metadata = {}
    # Attach validators to metadata
    if validators:
        metadata['validators'] = validators
    
    # Define field with appropriate parameters
    if default is not None:
        return field(default=default, metadata=metadata)
    elif default_factory is not None:
        return field(default_factory=default_factory, metadata=metadata)
    else:
        return field(metadata=metadata)

# Dataclass representing a User with validation
@dataclass
class User:
    # Define fields with validation
    name: str
    age: int = field_with_validation(default=0, validators=[
        validator(lambda instance, value: value >= 0 or ValidationError(""Age must be non-negative"")),
        validator(lambda instance, value: value <= 150 or ValidationError(""Age must be 150 or less""))
    ])
    email: str = field_with_validation(default="""", validators=[
        validator(lambda instance, value: ""@"" in value or ValidationError(""Invalid email address""))
    ])

# Example usage
try:
    user = User(name=""Arsen"", age=30, email=""arsen@example.com"")
    validate(user)
    print(""User is valid"")
except ValidationError as e:
    print(f""Validation error: {e}"")",0,W3RESOURCE,NA,PYTHON
,"import numpy as np

ids = np.array([101, 102, 103, 104, 105])
heights = np.array([165, 170.5, 168.2, 172, 160.4])
idx = np.argsort(heights)
print(""Indices:"", idx)
print(""Sorted IDs:"", ids[idx])",1,DEEPAI,Write a NumPy program to sort the student id with increasing height of the students from given students id and height. Print the integer indices that describes the sort order by multiple columns and the sorted data,PYTHON
,"import heapq

# Define a class to represent a node in the graph
class Node:
    def __init__(self, state, parent=None, action=None, cost=0, heuristic=0):
        self.state = state            # Current state
        self.parent = parent          # Parent node
        self.action = action          # Action taken to reach this node
        self.cost = cost              # Cost from start node to this node
        self.heuristic = heuristic    # Heuristic estimate of cost to goal

    # Compare nodes based on total cost (cost + heuristic)
    def __lt__(self, other):
        return (self.cost + self.heuristic) < (other.cost + other.heuristic)

# Define the A* search function
def astar_search(start_state, goal_state, actions, transition_model, cost_fn, heuristic_fn):
    # Initialize start node
    start_node = Node(state=start_state, cost=0, heuristic=heuristic_fn(start_state))

    # Priority queue for open nodes
    open_nodes = []
    heapq.heappush(open_nodes, start_node)

    # Set of explored states
    explored = set()

    while open_nodes:
        # Pop node with lowest total cost from priority queue
        current_node = heapq.heappop(open_nodes)

        # Check if goal state reached
        if current_node.state == goal_state:
            return get_solution(current_node)

        # Add current state to explored set
        explored.add(current_node.state)

        # Generate successor states
        for action in actions(current_node.state):  # Fix: Call actions function with current state
            next_state = transition_model(current_node.state, action)
            if next_state not in explored:
                cost = current_node.cost + cost_fn(current_node.state, action, next_state)
                heuristic = heuristic_fn(next_state)
                next_node = Node(state=next_state, parent=current_node, action=action, cost=cost, heuristic=heuristic)
                heapq.heappush(open_nodes, next_node)

    return None  # No solution found

# Function to reconstruct the solution path
def get_solution(node):
    path = []
    while node:
        path.append((node.state, node.action))
        node = node.parent
    return list(reversed(path))

# Example usage:
if __name__ == ""__main__"":
    # Define example functions and parameters for pathfinding problem
    def actions(state):
        return ['up', 'down', 'left', 'right']

    def transition_model(state, action):
        if action == 'up':
            return (state[0] - 1, state[1])
        elif action == 'down':
            return (state[0] + 1, state[1])
        elif action == 'left':
            return (state[0], state[1] - 1)
        elif action == 'right':
            return (state[0], state[1] + 1)

    def cost_fn(state, action, next_state):
        return 1

    def heuristic_fn(state):
        return abs(state[0] - goal_state[0]) + abs(state[1] - goal_state[1])

    # Define start and goal states
    start_state = (0, 0)
    goal_state = (3, 3)

    # Perform A* search
    solution = astar_search(start_state, goal_state, actions, transition_model, cost_fn, heuristic_fn)
    print(""Solution:"", solution)
",0,W3RESOURCE,NA,PYTHON
,"import numpy as np

dt = [('name', 'U20'), ('height', 'f4'), ('class', 'i4')]
data = np.array([('Alice', 165, 2), ('Bob', 170.5, 1), ('Charlie', 168.2, 2), ('David', 172, 1), ('Eve', 160.4, 3)], dtype=dt)
print(np.sort(data, order=['class', 'height']))",1,DEEPAI,"Write a NumPy program to create a structured array from given student name, height, class and their data types. Now sort by class, then height if class are equal.",PYTHON
,"import os  # Import the os module for interacting with the operating system
import shutil  # Import the shutil module for file operations
import argparse  # Import the argparse module for command-line argument parsing

def synchronize(source_dir, destination_dir):
    # Ensure both directories exist
    if not os.path.exists(source_dir):
        print(f""Source directory '{source_dir}' does not exist."")
        return
    if not os.path.exists(destination_dir):
        print(f""Destination directory '{destination_dir}' does not exist."")
        return

    # Iterate over files in source directory
    for root, dirs, files in os.walk(source_dir):
        # Get corresponding path in destination directory
        relative_path = os.path.relpath(root, source_dir)
        dest_path = os.path.join(destination_dir, relative_path)

        # Ensure corresponding directory structure exists in destination
        if not os.path.exists(dest_path):
            os.makedirs(dest_path)

        # Copy files from source to destination
        for file in files:
            source_file = os.path.join(root, file)
            dest_file = os.path.join(dest_path, file)
            shutil.copy2(source_file, dest_file)
            print(f""Copied: {source_file} -> {dest_file}"")

    print(""Synchronization complete."")

if __name__ == ""__main__"":
    # Create argument parser
    parser = argparse.ArgumentParser(description=""Synchronize files between two directories."")
    # Add argument for source directory
    parser.add_argument(""source"", help=""Source directory"")
    # Add argument for destination directory
    parser.add_argument(""destination"", help=""Destination directory"")
    # Parse the command-line arguments
    args = parser.parse_args()

    # Call the synchronize function with the provided arguments
    synchronize(args.source, args.destination)",0,W3RESOURCE,NA,PYTHON
,"import numpy as np
s = np.array([('A',160,10),('B',175,11),('C',155,9)],dtype=[('n','U10'),('h','i4'),('c','i4')])
print(np.sort(s,order='h'))
",1,PERPLEXITY,"Write a NumPy program to create a structured array from given student name, height, class and their data types. Now sort the array on height.",PYTHON
,"import json

# Define the Address and Person classes
class Address:
    def __init__(self, street, city, state, zip_code):
        self.street = street
        self.city = city
        self.state = state
        self.zip_code = zip_code

class Person:
    def __init__(self, name, age, address):
        self.name = name
        self.age = age
        self.address = address

# Custom JSON Encoder
class ComplexEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, Address):
            return {
                '__type__': 'Address',
                'street': obj.street,
                'city': obj.city,
                'state': obj.state,
                'zip_code': obj.zip_code
            }
        elif isinstance(obj, Person):
            return {
                '__type__': 'Person',
                'name': obj.name,
                'age': obj.age,
                'address': obj.address
            }
        return json.JSONEncoder.default(self, obj)

# Custom JSON Decoder
def complex_decoder(dct):
    if '__type__' in dct:
        if dct['__type__'] == 'Address':
            return Address(dct['street'], dct['city'], dct['state'], dct['zip_code'])
        elif dct['__type__'] == 'Person':
            address = dct['address']
            if isinstance(address, dict):
                address = complex_decoder(address)
            return Person(dct['name'], dct['age'], address)
    return dct

# Example usage
address = Address(""123 ABCD St."", ""Paris"", ""CA"", ""12345"")
person = Person(""Roslindis Bronwen"", 30, address)

# Serialize to JSON
person_json = json.dumps(person, cls=ComplexEncoder)
print(""Serialized JSON:"", person_json)

# Deserialize from JSON
decoded_person = json.loads(person_json, object_hook=complex_decoder)
print(""\nDecoded Object:"", decoded_person.name, decoded_person.age, decoded_person.address.street)",0,W3RESOURCE,NA,PYTHON
,"import numpy as np
a = np.array([[4,6],[2,1]])
print(np.sort(a,0), np.sort(a,1), np.sort(a, None), sep='\n')
",1,PERPLEXITY,"Write a NumPy program to sort a given array of shape 2 along the first axis, last axis and on flattened array.",PYTHON
,"import hashlib

class BloomFilter:
    def __init__(self, size, hash_count):
        self.size = size  # Size of the bit array
        self.hash_count = hash_count  # Number of hash functions
        self.bit_array = [0] * size  # Bit array to store elements

    def _hashes(self, item):
        """"""Generate hash_count hashes for the item using different hash functions.""""""
        hashes = []
        for i in range(self.hash_count):
            # Create a unique hash for each iteration
            hash_result = int(hashlib.md5((str(item) + str(i)).encode()).hexdigest(), 16) % self.size
            hashes.append(hash_result)
        return hashes

    def add(self, item):
        """"""Add an item to the Bloom filter.""""""
        hashes = self._hashes(item)
        for hash_value in hashes:
            self.bit_array[hash_value] = 1

    def check(self, item):
        """"""Check if an item is possibly in the Bloom filter.""""""
        hashes = self._hashes(item)
        return all(self.bit_array[hash_value] == 1 for hash_value in hashes)

# Example usage
size = 1000  # Size of the bit array
hash_count = 10  # Number of hash functions

bloom_filter = BloomFilter(size, hash_count)

# Add items to the Bloom filter
bloom_filter.add(""Red"")
bloom_filter.add(""Green"")
bloom_filter.add(""Blue"")
bloom_filter.add(""Orange"")

# Check for item membership
print(""Red in filter:"", bloom_filter.check(""Red""))  # Should be True
print(""Green in filter:"", bloom_filter.check(""Green""))  # Should be True
print(""Orange in filter:"", bloom_filter.check(""Orange""))  # Should be True
print(""Black in filter:"", bloom_filter.check(""Black""))  # Should be False (most likely)",0,W3RESOURCE,NA,PYTHON
,"import numpy as np

x = np.arange(7)
print(""Original:"", x)
print(""Powers (element-wise ^3):"", np.power(x, 3))
",1,PERPLEXITY,Write a NumPy program to get the powers of an array values element-wise.,PYTHON
,"# Import the asyncio library for asynchronous programming
import asyncio

# Import nest_asyncio to handle nested event loops
import nest_asyncio

# Apply nest_asyncio to allow nested event loops
nest_asyncio.apply()

# Define the TaskScheduler class
class TaskScheduler:
    def __init__(self):
        # Initialize an empty list to store tasks
        self.tasks = []

    def schedule(self, coro, *args):
        """"""Schedule a coroutine with given arguments.""""""
        # Append the coroutine with its arguments to the tasks list
        self.tasks.append(coro(*args))

    async def run(self):
        """"""Run all scheduled tasks concurrently.""""""
        # Use asyncio.gather to run all tasks concurrently
        await asyncio.gather(*self.tasks)

# Define an example coroutine that simulates a task
async def example_task(name, duration):
    """"""An example coroutine that simulates a task.""""""
    # Print a message when the task starts
    print(f""Task {name} started, will take {duration} seconds."")
    # Simulate a delay using asyncio.sleep
    await asyncio.sleep(duration)
    # Print a message when the task finishes
    print(f""Task {name} finished."")

# Define the main coroutine for example usage
async def main():
    # Create an instance of TaskScheduler
    scheduler = TaskScheduler()

    # Schedule example tasks with different durations
    scheduler.schedule(example_task, ""A"", 2)
    scheduler.schedule(example_task, ""B"", 3)
    scheduler.schedule(example_task, ""C"", 1)

    # Run all scheduled tasks concurrently
    await scheduler.run()

# Run the main function using asyncio's event loop
asyncio.run(main())",0,W3RESOURCE,NA,PYTHON
,"import numpy as np

x = np.arange(10)
print(""Original:"", x)
print(""Floor division by 3:"", np.floor_divide(x, 3))
",1,PERPLEXITY,Write a NumPy program to get the largest integer smaller or equal to the division of the inputs.,PYTHON
,"from collections import OrderedDict

# Define a class for the caching system with LRU eviction policy
class LRUCache:
    # Initialize the cache with a maximum capacity
    def __init__(self, capacity):
        self.capacity = capacity  # Set the maximum capacity
        self.cache = OrderedDict()  # Use OrderedDict for O(1) access and ordering

    # Get the value associated with the key from the cache
    def get(self, key):
        # If the key is not in the cache, return -1
        if key not in self.cache:
            return -1
        # Move the accessed key to the end to indicate recent use
        self.cache.move_to_end(key)
        # Return the value associated with the key
        return self.cache[key]

    # Put a key-value pair into the cache
    def put(self, key, value):
        # If the key is already in the cache, update its value and move it to the end
        if key in self.cache:
            self.cache[key] = value
            self.cache.move_to_end(key)
        else:
            # If the cache is at capacity, remove the least recently used item
            if len(self.cache) == self.capacity:
                self.cache.popitem(last=False)  # Remove the first item (least recently used)
            # Add the new key-value pair to the cache
            self.cache[key] = value

# Example usage
if __name__ == ""__main__"":
    # Create a cache with a capacity of 2
    cache = LRUCache(2)
    # Put key-value pairs into the cache
    cache.put(1, 1)
    cache.put(2, 2)
    # Retrieve and print the value associated with key 1 (should be 1)
    print(cache.get(1))
    # Put a new key-value pair into the cache (evicting key 2)
    cache.put(3, 3)
    # Retrieve and print the value associated with key 2 (should be -1, as it was evicted)
    print(cache.get(2))
    # Retrieve and print the value associated with key 3 (should be 3)
    print(cache.get(3))",0,W3RESOURCE,NA,PYTHON
,"import numpy as np

x = np.arange(10)
print(""Original:"", x)
print(""True division by 3:"", x / 3)
",1,PERPLEXITY,"
Write a NumPy program to get true division of the element-wise array inputs.",PYTHON
,"# Import the Abstract Syntax Tree (AST) module
import ast

# Import the math module for mathematical functions and constants
import math

# Define a class for evaluating mathematical expressions
class MathExpressionEvaluator:
    def __init__(self):
        pass

    # Method to evaluate mathematical expressions
    def evaluate(self, expression):
        try:
            # Parse the expression into an Abstract Syntax Tree (AST)
            parsed_expression = ast.parse(expression, mode='eval')

            # Define the allowed names (functions and constants) for evaluation
            allowed_names = {
                'sin': math.sin,
                'cos': math.cos,
                'tan': math.tan,
                'log': math.log,
                'sqrt': math.sqrt,
                **vars(math)  # Include all functions and constants from the math module
            }

            # Evaluate the AST using a custom namespace that includes the allowed names
            result = eval(compile(parsed_expression, filename='', mode='eval'), {}, allowed_names)
            return result
        except SyntaxError:
            print(""Invalid expression syntax."")
            return None
        except Exception as e:
            print(""Error:"", e)
            return None

# Example usage
if __name__ == ""__main__"":
    evaluator = MathExpressionEvaluator()

    # Evaluate mathematical expressions
    print(""Evaluation Results:"")
    print(""10 + 12 * 4 ="", evaluator.evaluate(""10 + 12 * 4""))
    print(""(12 + 13) * 4 ="", evaluator.evaluate(""(12 + 13) * 4""))
    print(""sin(0.5) ="", evaluator.evaluate(""sin(0.5)""))
    print(""log(10) ="", evaluator.evaluate(""log(10)""))",0,W3RESOURCE,NA,PYTHON
,"import numpy as np

print(np.logaddexp(np.log(1e-50), np.log(2.5e-50)))
print(np.logaddexp2(np.log(1e-50), np.log(2.5e-50)))
",1,PERPLEXITY,"Write a NumPy program to compute logarithm of the sum of exponentiations of the inputs, sum of exponentiations of the inputs in base-2.",PYTHON
,"# Import necessary modules
import json
import threading
import time
import signal
import os
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler

# Define the ConfigManager class to manage configurations
class ConfigManager:
    def __init__(self, config_file):
        # Initialize with the configuration file path
        self.config_file = config_file
        # Initialize the configuration data dictionary
        self.config_data = {}
        # Create a lock for thread-safe operations
        self.lock = threading.Lock()
        # Load the initial configuration
        self.load_config()

    def load_config(self):
        # Load the configuration file in a thread-safe manner
        with self.lock:
            with open(self.config_file, 'r') as f:
                self.config_data = json.load(f)
        # Print the loaded configuration for debugging
        print(""Configuration reloaded:"", self.config_data)

    def get_config(self):
        # Get the current configuration in a thread-safe manner
        with self.lock:
            return self.config_data

    def start_watching(self):
        # Create a file system event handler for the configuration file
        event_handler = ConfigFileHandler(self, self.config_file)
        # Create an observer to monitor file system changes
        observer = Observer()
        # Schedule the observer to watch the current directory for changes
        observer.schedule(event_handler, path='.', recursive=False)
        # Start the observer
        observer.start()
        print(""Started watching for configuration changes..."")
        
        try:
            # Continuously check if the stop event is set
            while not stop_event.is_set():
                time.sleep(1)
        except KeyboardInterrupt:
            pass
        finally:
            # Stop the observer when shutting down
            print(""Stopping observer..."")
            observer.stop()
            observer.join()
            print(""Observer stopped."")

# Define the file system event handler class for configuration file changes
class ConfigFileHandler(FileSystemEventHandler):
    def __init__(self, config_manager, config_file):
        # Initialize with the config manager and the configuration file path
        self.config_manager = config_manager
        self.config_file = os.path.abspath(config_file)

    def on_modified(self, event):
        # Check if the modified file is the configuration file
        if os.path.abspath(event.src_path) == self.config_file:
            # Print the modification event for debugging
            print(f""Configuration file {event.src_path} changed, reloading..."")
            # Reload the configuration
            self.config_manager.load_config()

# Define a signal handler for SIGINT to handle graceful shutdown
def handle_sigint(signal, frame):
    global stop_event
    print(""Shutting down..."")
    # Set the stop event to terminate the program
    stop_event.set()

# Example usage
if __name__ == ""__main__"":
    # Define the path to the configuration file
    config_file = 'config.json'
    # Create an instance of ConfigManager with the configuration file
    config_manager = ConfigManager(config_file)

    # Create an event to signal stopping
    stop_event = threading.Event()
    # Register the signal handler for SIGINT
    signal.signal(signal.SIGINT, handle_sigint)
    
    # Start watching for configuration changes in a separate thread
    watcher_thread = threading.Thread(target=config_manager.start_watching)
    watcher_thread.start()

    # Simulate application usage
    try:
        while not stop_event.is_set():
            # Get and print the current configuration periodically
            config = config_manager.get_config()
            print(""Current configuration:"", config)
            time.sleep(5)
    except KeyboardInterrupt:
        pass

    # Signal the watcher thread to stop
    stop_event.set()
    # Wait for the watcher thread to finish
    watcher_thread.join()
    print(""Program terminated."")",0,W3RESOURCE,NA,PYTHON
,"import numpy as np

print(""Add:"", np.add(1.0, 4.0))
print(""Subtract:"", np.subtract(1.0, 4.0))
print(""Multiply:"", np.multiply(1.0, 4.0))
print(""Divide:"", np.divide(1.0, 4.0))
",1,PERPLEXITY,"Write a NumPy program to add, subtract, multiply, divide arguments element-wise.",PYTHON
,"# Import the random module for generating random numbers
import random
# Import the numpy module for numerical operations
import numpy as np

# Problem definition: Example function to optimize (e.g., Rastrigin function)
def rastrigin(x):
    # Define the constant A
    A = 10
    # Compute the Rastrigin function value for the input x
    return A * len(x) + sum([(xi**2 - A * np.cos(2 * np.pi * xi)) for xi in x])

# GA Parameters
# Set the population size
population_size = 100
# Set the genome length (number of genes in a chromosome)
genome_length = 10
# Set the crossover rate
crossover_rate = 0.8
# Set the mutation rate
mutation_rate = 0.01
# Set the number of generations
num_generations = 100
# Define the bounds for the gene values
bounds = [-5.12, 5.12]

# Initialization
def initialize_population(pop_size, genome_len, bounds):
    # Generate a population of random individuals within the given bounds
    return [np.random.uniform(bounds[0], bounds[1], genome_len) for _ in range(pop_size)]

# Fitness function
def evaluate_fitness(population):
    # Evaluate the fitness of each individual in the population using the Rastrigin function
    return [rastrigin(individual) for individual in population]

# Selection (Tournament Selection)
def tournament_selection(population, fitness, tournament_size=3):
    # Initialize the list of selected individuals
    selected = []
    # Select individuals based on tournament selection
    for _ in range(len(population)):
        # Choose random aspirants for the tournament
        aspirants = [random.randint(0, len(population) - 1) for _ in range(tournament_size)]
        # Select the individual with the best fitness among the aspirants
        selected.append(min(aspirants, key=lambda aspirant: fitness[aspirant]))
    # Return the selected individuals
    return [population[i] for i in selected]

# Crossover (Single Point Crossover)
def single_point_crossover(parent1, parent2):
    # Perform crossover with a given probability
    if random.random() < crossover_rate:
        # Choose a random crossover point
        point = random.randint(1, len(parent1) - 1)
        # Create children by combining the parents at the crossover point
        child1 = np.concatenate([parent1[:point], parent2[point:]])
        child2 = np.concatenate([parent2[:point], parent1[point:]])
        # Return the children
        return child1, child2
    # If no crossover, return the parents as is
    return parent1, parent2

# Mutation
def mutate(individual, mutation_rate, bounds):
    # Mutate each gene with a given probability
    for i in range(len(individual)):
        if random.random() < mutation_rate:
            # Replace the gene with a random value within the bounds
            individual[i] = np.random.uniform(bounds[0], bounds[1])
    # Return the mutated individual
    return individual

# Genetic Algorithm
def genetic_algorithm():
    # Initialize the population
    population = initialize_population(population_size, genome_length, bounds)
    
    # Iterate over the number of generations
    for generation in range(num_generations):
        # Evaluate the fitness of the population
        fitness = evaluate_fitness(population)
        
        # Selection
        # Select individuals based on their fitness
        selected_population = tournament_selection(population, fitness)
        
        # Crossover
        # Create the next generation through crossover
        next_population = []
        for i in range(0, len(selected_population), 2):
            parent1 = selected_population[i]
            parent2 = selected_population[min(i + 1, len(selected_population) - 1)]
            child1, child2 = single_point_crossover(parent1, parent2)
            next_population.extend([child1, child2])
        
        # Mutation
        # Mutate the individuals in the next generation
        population = [mutate(individual, mutation_rate, bounds) for individual in next_population]
        
        # Evaluation
        # Re-evaluate the fitness of the new population
        fitness = evaluate_fitness(population)
        # Find the best fitness and corresponding individual
        best_fitness = min(fitness)
        best_individual = population[fitness.index(best_fitness)]
        
        # Print the best fitness of the current generation
        print(f'Generation {generation + 1}: Best Fitness = {best_fitness}')
    
    # Return the best individual found
    return best_individual

# Uncomment the line below to run the genetic algorithm
best_solution = genetic_algorithm()
# Print the best solution found
print(""Best solution found:"", best_solution)",0,W3RESOURCE,NA,PYTHON
,"def abc():
    x = 1
    y = 2
    str1 = ""w3resource""
    print(""Python Exercises"")

print(abc.__code__.co_nlocals)  # Output: 3
",1,PERPLEXITY,Write a Python program to detect the number of local variables declared in a function.,PYTHON
,"# Define a function that returns the maximum of two numbers
def max_of_two(x, y):
    # Check if x is greater than y
    if x > y:
        # If x is greater, return x
        return x
    # If y is greater or equal to x, return y
    return y

# Define a function that returns the maximum of three numbers
def max_of_three(x, y, z):
    # Call max_of_two function to find the maximum of y and z,
    # then compare it with x to find the overall maximum
    return max_of_two(x, max_of_two(y, z))

# Print the result of calling max_of_three function with arguments 3, 6, and -5
print(max_of_three(3, 6, -5)) ",0,W3RESOURCE,NA,PYTHON
,"def test(a):
    def add(b):
        nonlocal a
        a += 1
        return a + b
    return add

a = int(input(""Enter value for a: ""))
func = test(a)
b = int(input(""Enter value for b: ""))
print(""Result:"", func(b))
",1,PERPLEXITY,Write a Python program to access a function inside a function.,PYTHON
,"# Define a function named 'sum' that takes a list of numbers as input
def sum(numbers):
    # Initialize a variable 'total' to store the sum of numbers, starting at 0
    total = 0
    
    # Iterate through each element 'x' in the 'numbers' list
    for x in numbers:
        # Add the current element 'x' to the 'total'
        total += x
    
    # Return the final sum stored in the 'total' variable
    return total

# Print the result of calling the 'sum' function with a tuple of numbers (8, 2, 3, 0, 7)
print(sum((8, 2, 3, 0, 7))) ",0,,NA,PYTHON
,"code = input(""Enter Python code: "")
exec(code)
",1,PERPLEXITY,Write a Python program to execute a string containing Python code,PYTHON
,"# Define a function named 'multiply' that takes a list of numbers as input
def multiply(numbers):
    # Initialize a variable 'total' to store the multiplication result, starting at 1
    total = 1
    
    # Iterate through each element 'x' in the 'numbers' list
    for x in numbers:
        # Multiply the current element 'x' with the 'total'
        total *= x
    
    # Return the final multiplication result stored in the 'total' variable
    return total

# Print the result of calling the 'multiply' function with a tuple of numbers (8, 2, 3, -1, 7)
print(multiply((8, 2, 3, -1, 7))) ",0,W3RESOURCE,NA,PYTHON
,"def bold(fn): return lambda: f""<b>{fn()}</b>""
def italic(fn): return lambda: f""<i>{fn()}</i>""
def underline(fn): return lambda: f""<u>{fn()}</u>""

text = input(""Enter text: "")
hello = underline(italic(bold(lambda: text)))
print(hello())
",1,PERPLEXITY,"Write a Python program to create a chain of function decorators (bold, italic, underline etc.).",PYTHON
,"# Define a function named 'string_reverse' that takes a string 'str1' as input
def string_reverse(str1):
    # Initialize an empty string 'rstr1' to store the reversed string
    rstr1 = ''
    
    # Calculate the length of the input string 'str1'
    index = len(str1)
    
    # Execute a while loop until 'index' becomes 0
    while index > 0:
        # Concatenate the character at index - 1 of 'str1' to 'rstr1'
        rstr1 += str1[index - 1]
        
        # Decrement the 'index' by 1 for the next iteration
        index = index - 1
    
    # Return the reversed string stored in 'rstr1'
    return rstr1

# Print the result of calling the 'string_reverse' function with the input string '1234abcd'
print(string_reverse('1234abcd'))",0,W3RESOURCE,NA,PYTHON
,"def printValues():
    l = [i**2 for i in range(1, 31)]
    print(l)

printValues()
",1,PERPLEXITY,"
Write a Python function to create and print a list where the values are the squares of numbers between 1 and 30 (both included).",PYTHON
,"# Define a function named 'factorial' that calculates the factorial of a number 'n'
def factorial(n):
    # Check if the number 'n' is 0
    if n == 0:
        # If 'n' is 0, return 1 (factorial of 0 is 1)
        return 1
    else:
        # If 'n' is not 0, recursively call the 'factorial' function with (n-1) and multiply it with 'n'
        return n * factorial(n - 1)

# Ask the user to input a number to compute its factorial and store it in variable 'n'
n = int(input(""Input a number to compute the factorial: ""))

# Print the factorial of the number entered by the user by calling the 'factorial' function
print(factorial(n))",0,W3RESOURCE,NA,PYTHON
,"# Input
user_input = input(""Enter hyphen-separated words: "")

# Process
items = [n for n in user_input.split('-')]
items.sort()
result = '-'.join(items)

# Output
print(""Sorted:"", result)
",1,PERPLEXITY,Write a Python program that accepts a hyphen-separated sequence of words as input and prints the words in a hyphen-separated sequence after sorting them alphabetically.,PYTHON
,"# Define a function named 'test_range' that checks if a number 'n' is within the range 3 to 8 (inclusive)
def test_range(n):
    # Check if 'n' is within the range from 3 to 8 (inclusive) using the 'in range()' statement
    if n in range(3, 9):
        # If 'n' is within the range, print that 'n' is within the given range
        print(""%s is in the range"" % str(n))
    else:
        # If 'n' is outside the range, print that the number is outside the given range
        print(""The number is outside the given range."")

# Call the 'test_range' function with the argument 5
test_range(5)",0,W3RESOURCE,NA,PYTHON
,"import string

def ispangram(str1, alphabet=string.ascii_lowercase):
    alphaset = set(alphabet)
    str_set = set(str1.lower())
    return alphaset <= str_set

# Test
print(ispangram('The quick brown fox jumps over the lazy dog'))  # True
",1,PERPLEXITY,Write a Python function to check whether a string is a pangram or not.,PYTHON
,"# Define a function named 'string_test' that counts the number of upper and lower case characters in a string 's'
def string_test(s):
    # Create a dictionary 'd' to store the count of upper and lower case characters
    d = {""UPPER_CASE"": 0, ""LOWER_CASE"": 0}
    
    # Iterate through each character 'c' in the string 's'
    for c in s:
        # Check if the character 'c' is in upper case
        if c.isupper():
            # If 'c' is upper case, increment the count of upper case characters in the dictionary
            d[""UPPER_CASE""] += 1
        # Check if the character 'c' is in lower case
        elif c.islower():
            # If 'c' is lower case, increment the count of lower case characters in the dictionary
            d[""LOWER_CASE""] += 1
        else:
            # If 'c' is neither upper nor lower case (e.g., punctuation, spaces), do nothing
            pass
    
    # Print the original string 's'
    print(""Original String: "", s)
    
    # Print the count of upper case characters
    print(""No. of Upper case characters: "", d[""UPPER_CASE""])
    
    # Print the count of lower case characters
    print(""No. of Lower case Characters: "", d[""LOWER_CASE""])

# Call the 'string_test' function with the input string 'The quick Brown Fox'
string_test('The quick Brown Fox')",0,W3RESOURCE,NA,PYTHON
,"def pascal_triangle(n):
    for i in range(n):
        row = [1]
        for j in range(1, i):
            row.append(row[j-1] + row[j])
        row.append(1) if i > 0 else None
        print(row)

# Test
pascal_triangle(6)
",1,PERPLEXITY,Write a Python function that prints out the first n rows of Pascal's triangle.,PYTHON
,"# Define a function named 'unique_list' that takes a list 'l' as input and returns a list of unique elements
def unique_list(l):
    # Create an empty list 'x' to store unique elements
    x = []
    
    # Iterate through each element 'a' in the input list 'l'
    for a in l:
        # Check if the element 'a' is not already present in the list 'x'
        if a not in x:
            # If 'a' is not in 'x', add it to the list 'x'
            x.append(a)
    
    # Return the list 'x' containing unique elements
    return x

# Print the result of calling the 'unique_list' function with a list containing duplicate elements
print(unique_list([1, 2, 3, 3, 3, 3, 4, 5]))  ",0,W3RESOURCE,NA,PYTHON
,"def isPalindrome(string):
    left_pos = 0
    right_pos = len(string) - 1
    
    while right_pos >= left_pos:
        if string[left_pos] != string[right_pos]:
            return False
        left_pos += 1
        right_pos -= 1
    
    return True

# Test
print(isPalindrome('aza'))  # True
",1,PERPLEXITY,Write  a Python function that checks whether a passed string is a palindrome or not.,PYTHON
,"# Define a function named 'test_prime' that checks if a number 'n' is a prime number
def test_prime(n):
    # Check if 'n' is equal to 1
    if (n == 1):
        # If 'n' is 1, return False (1 is not a prime number)
        return False
    # Check if 'n' is equal to 2
    elif (n == 2):
        # If 'n' is 2, return True (2 is a prime number)
        return True
    else:
        # Iterate through numbers from 2 to (n-1) using 'x' as the iterator
        for x in range(2, n):
            # Check if 'n' is divisible by 'x' without any remainder
            if (n % x == 0):
                # If 'n' is divisible by 'x', return False (not a prime number)
                return False
        # If 'n' is not divisible by any number from 2 to (n-1), return True (prime number)
        return True

# Print the result of checking if 9 is a prime number by calling the 'test_prime' function
print(test_prime(9))",0,W3RESOURCE,NA,PYTHON
,"def perfect_number(n):
    sum_div = 0
    for x in range(1, n):
        if n % x == 0:
            sum_div += x
    return sum_div == n

# Test
print(perfect_number(6))  # True (1+2+3=6)
",1,PERPLEXITY,"Write a Python function to check whether a number is ""Perfect"" or not.",PYTHON
,"# Define a function named 'is_even_num' that takes a list 'l' as input and returns a list of even numbers
def is_even_num(l):
    # Create an empty list 'enum' to store even numbers
    enum = []
    
    # Iterate through each number 'n' in the input list 'l'
    for n in l:
        # Check if the number 'n' is even (divisible by 2 without a remainder)
        if n % 2 == 0:
            # If 'n' is even, append it to the 'enum' list
            enum.append(n)
    
    # Return the list 'enum' containing even numbers
    return enum

# Print the result of calling the 'is_even_num' function with a list of numbers
print(is_even_num([1, 2, 3, 4, 5, 6, 7, 8, 9])) ",0,W3RESOURCE,NA,PYTHON
,"def is_even_num(l):
    return [n for n in l if n % 2 == 0]

# Example usage
print(is_even_num([1, 2, 3, 4, 5, 6, 7, 8, 9]))
",1,PERPLEXITY,Write a Python program to print the even numbers from a given list.,PYTHON
,"# Define a function named 'perfect_number' that checks if a number 'n' is a perfect number
def perfect_number(n):
    # Initialize a variable 'sum' to store the sum of factors of 'n'
    sum = 0
    
    # Iterate through numbers from 1 to 'n-1' using 'x' as the iterator
    for x in range(1, n):
        # Check if 'x' is a factor of 'n' (divides 'n' without remainder)
        if n % x == 0:
            # If 'x' is a factor of 'n', add it to the 'sum'
            sum += x
    
    # Check if the 'sum' of factors is equal to the original number 'n'
    return sum == n

# Print the result of checking if 6 is a perfect number by calling the 'perfect_number' function
print(perfect_number(6))",0,W3RESOURCE,NA,PYTHON
,"def test_prime(n):
    if n <= 1:
        return False
    for x in range(2, n):
        if n % x == 0:
            return False
    return True

# Accepts input from user
n = int(input(""Enter a number: ""))
print(test_prime(n))
",1,PERPLEXITY,"Write a Python function that takes a number as a parameter and checks whether the number is prime or not.

Note : A prime number (or a prime) is a natural number greater than 1 and that has no positive divisors other than 1 and itself.",PYTHON
,"# Define a function named 'isPalindrome' that checks if a string is a palindrome
def isPalindrome(string):
    # Initialize left and right pointers to check characters from the start and end of the string
    left_pos = 0
    right_pos = len(string) - 1
    
    # Loop until the pointers meet or cross each other
    while right_pos >= left_pos:
        # Check if the characters at the left and right positions are not equal
        if not string[left_pos] == string[right_pos]:
            # If characters don't match, return False (not a palindrome)
            return False
        
        # Move the left pointer to the right and the right pointer to the left to continue checking
        left_pos += 1
        right_pos -= 1
    
    # If the loop finishes without returning False, the string is a palindrome, so return True
    return True

# Print the result of checking if the string 'aza' is a palindrome by calling the 'isPalindrome' function
print(isPalindrome('aza')) ",0,W3RESOURCE,NA,PYTHON

,"def unique_list(l):

    return list(set(l))



# Example usage

print(unique_list([1, 2, 3, 3, 3, 3, 4, 5]))
",1,PERPLEXITY,Write a Python function that takes a list and returns a new list with distinct elements from the first list.,PYTHON

,"# Define a function named 'pascal_triangle' that generates Pascal's Triangle up to row 'n'
def pascal_triangle(n):
    # Initialize the first row of Pascal's Triangle with value 1 as a starting point
    trow = [1]
    
    # Create a list 'y' filled with zeros to be used for calculations
    y = [0]
    
    # Iterate through a range starting from 0 up to the maximum of 'n' or 0 (taking the maximum to handle negative 'n')
    for x in range(max(n, 0)):
        # Print the current row of Pascal's Triangle
        print(trow)
        
        # Update the current row based on the previous row by calculating the next row using list comprehension
        # The formula for generating the next row in Pascal's Triangle is based on addition of consecutive elements
        trow = [l + r for l, r in zip(trow + y, y + trow)]
    
    # Return True if 'n' is greater than or equal to 1, else return False
    return n >= 1

# Generate Pascal's Triangle up to row 6 by calling the 'pascal_triangle' function
pascal_triangle(6) ",0,W3RESOURCE,NA,PYTHON
,"def string_test(s):
    upper_count = 0
    lower_count = 0

    for ch in s:
        if ch.isupper():
            upper_count += 1
        elif ch.islower():
            lower_count += 1

    print(""No. of Upper case characters :"", upper_count)
    print(""No. of Lower case Characters :"", lower_count)

# Example usage
string_test('The quick Brow Fox')
",1,PERPLEXITY,"Write a Python function that accepts a string and counts the number of upper and lower case letters.

Sample String : 'The quick Brow Fox'
Expected Output :
No. of Upper case characters : 3
No. of Lower case Characters : 12",PYTHON
,"# Import the 'string' and 'sys' modules
import string
import sys

# Define a function named 'ispangram' that checks if a string is a pangram
def ispangram(str1, alphabet=string.ascii_lowercase):
    # Create a set 'alphaset' containing all lowercase letters from the provided alphabet
    alphaset = set(alphabet)
    
    # Convert the input string to lowercase and create a set from it
    str_set = set(str1.lower())
    
    # Check if the set of lowercase characters in the input string covers all characters in 'alphaset'
    return alphaset <= str_set

# Print the result of checking if the string is a pangram by calling the 'ispangram' function
print(ispangram('The quick brown fox jumps over the lazy dog')) 
",0,W3RESOURCE,NA,PYTHON
,"def in_range(n, low, high):
    return low <= n <= high

# ---------- INPUT ----------
n, low, high = 5, 3, 8

# ---------- OUTPUT ----------
if in_range(n, low, high):
    print(f""{n} is in the range {low} to {high}"")
else:
    print(f""{n} is outside the range {low} to {high}"")
",1,GPT,Write a Python function to check whether a number falls within a given range.,PYTHON
,"# Take user input and split it into a list based on the hyphen (""-"") separator, creating a list named 'items'
items = [n for n in input().split('-')]

# Sort the elements in the 'items' list in lexicographical order (alphabetical and numerical sorting)
items.sort()

# Join the sorted elements in the 'items' list using the hyphen (""-"") separator and print the resulting string
print('-'.join(items)) ",0,W3RESOURCE,NA,PYTHON
,"def factorial(n):
    if n == 0:
        return 1
    return n * factorial(n - 1)

# General usage
print(factorial(6))  # Output: 720
",1,PERPLEXITY,Write a Python function to calculate the factorial of a number (a non-negative integer). The function accepts the number as an argument.,PYTHON
,"# Define a function named 'printValues' that generates a list of squares of numbers from 1 to 20
def printValues():
    # Create an empty list 'l'
    l = list()
    
    # Iterate through numbers from 1 to 20 (inclusive)
    for i in range(1, 21):
        # Calculate the square of 'i' and append it to the list 'l'
        l.append(i**2)
    
    # Print the list containing squares of numbers from 1 to 20
    print(l)

# Call the 'printValues' function to generate and print the list of squares
printValues() ",0,W3RESOURCE,NA,PYTHON
,"def string_reverse(text):
    return text[::-1]

# General usage
input_string = ""python""
print(string_reverse(input_string))  # Output: ""nohtyp""
",1,PERPLEXITY,"Write a Python program to reverse a string.
Sample String : ""1234abcd""
Expected Output : ""dcba4321"" dont give the code for this particular samples , give it in a general way of i/o",PYTHON
,"# Define a decorator 'make_bold' that adds bold HTML tags to the wrapped function's return value
def make_bold(fn):
    def wrapped():
        return ""<b>"" + fn() + ""</b>""
    return wrapped

# Define a decorator 'make_italic' that adds italic HTML tags to the wrapped function's return value
def make_italic(fn):
    def wrapped():
        return ""<i>"" + fn() + ""</i>""
    return wrapped

# Define a decorator 'make_underline' that adds underline HTML tags to the wrapped function's return value
def make_underline(fn):
    def wrapped():
        return ""<u>"" + fn() + ""</u>""
    return wrapped

# Apply multiple decorators (@make_bold, @make_italic, @make_underline) to the 'hello' function
@make_bold
@make_italic
@make_underline
def hello():
    return ""hello world""

# Print the result of the decorated 'hello' function, which adds HTML tags for bold, italic, and underline

print(hello()) ## returns ""<b><i><u>hello world</u></i></b>""",0,W3RESOURCE,NA,PYTHON
,"def multiply_numbers(numbers):
    return 1 if not numbers else numbers[0] * multiply_numbers(numbers[1:])

# Or using reduce (from functools)
from functools import reduce
def multiply_numbers(numbers):
    return reduce(lambda x, y: x * y, numbers, 1)

print(multiply_numbers([8, 2, 3, -1, 7]))  # Output: -336
",1,PERPLEXITY,"Write a Python function to multiply all the numbers in a list.                                      Sample List : (8, 2, 3, -1, 7)
Expected Output : -336",PYTHON
,"# Define a string variable 'mycode' containing a Python code as a string
mycode = 'print(""hello world"")'

# Define a multi-line string variable 'code' containing Python code as a string
code = """"""
def mutiply(x,y):
    return x*y

print('Multiply of 2 and 3 is: ',mutiply(2,3))
""""""

# Execute the Python code represented by the string stored in the variable 'mycode'
exec(mycode)

# Execute the Python code represented by the multi-line string stored in the variable 'code'
exec(code) ",0,W3RESOURCE,NA,PYTHON
,"def sum_numbers(numbers):
    return sum(numbers)

print(sum_numbers([8, 2, 3, 0, 7]))  # Output: 20
",1,PERPLEXITY,"Write a Python function to sum all the numbers in a list.
Sample List : (8, 2, 3, 0, 7)
Expected Output : 20",PYTHON
,"# Define a function named 'test' that takes a parameter 'a'
def test(a):
    # Define a nested function 'add' that takes a parameter 'b'
    def add(b):
        # Declare 'a' from the outer scope as nonlocal to modify its value
        nonlocal a
        
        # Increment the value of 'a' by 1
        a += 1
        
        # Return the sum of 'a' (modified by the nonlocal statement) and 'b'
        return a + b
    
    # Return the inner function 'add' and its scope is retained due to closure
    return add

# Call the 'test' function with an argument '4' and assign the returned function to 'func'
func = test(4)

# Call the function 'func' with argument '4' and print the result
print(func(4)) ",0,W3RESOURCE,NA,PYTHON
,"def max_of_three(a, b, c):
    return max(a, b, c)

# ---------- INPUT ----------
x, y, z = 3, 6, -5

# ---------- OUTPUT ----------
print(""Maximum:"", max_of_three(x, y, z))
",1,GPT,Write a Python function to find the maximum of three numbers.,PYTHON
,"# Define a function named 'abc'
def abc():
    # Define and assign values to local variables 'x', 'y', and 'str1' inside the function 'abc'
    x = 1
    y = 2
    str1 = ""w3resource""
    
    # Print the string ""Python Exercises""
    print(""Python Exercises"")

# Access the number of local variables in the function 'abc' using the __code__.co_nlocals attribute
print(abc.__code__.co_nlocals) ",0,W3RESOURCE,NA,PYTHON
,"import random, numpy as np

f = lambda x: 10*len(x) + sum(x*x - 10*np.cos(2*np.pi*x))

def GA(pop=50, n=5, gen=50):
    P = [np.random.uniform(-5,5,n) for _ in range(pop)]
    for g in range(gen):
        P = sorted(P, key=f)
        print(f""Gen {g+1} Best:"", f(P[0]))
        N = P[:10]
        while len(N)<pop:
            a,b = random.sample(P[:20],2)
            p = random.randint(1,n-1)
            c = np.r_[a[:p], b[p:]]
            c += np.random.uniform(-0.1,0.1,n)*(np.random.rand(n)<0.1)
            N.append(c)
        P = N
    return P[0]
",1,GPT,Write AN EFFECTIVE SHORTEST LINE OF Python program to implement a genetic algorithm for solving optimization problems.,PYTHON
,"# Importing the NumPy library
import numpy as np

# Displaying a message for addition operation
print(""Add:"")
# Performing addition
print(np.add(1.0, 4.0))

# Displaying a message for subtraction operation
print(""Subtract:"")
# Performing subtraction
print(np.subtract(1.0, 4.0))

# Displaying a message for multiplication operation
print(""Multiply:"")
# Performing multiplication
print(np.multiply(1.0, 4.0))

# Displaying a message for division operation
print(""Divide:"")
# Performing division
print(np.divide(1.0, 4.0))",0,W3RESOURCE,NA,PYTHON
,"import json, threading, time, signal, os
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler

class Config:
    def __init__(s,f):
        s.f, s.d, s.l = f, {}, threading.Lock()
        s.load()

    def load(s):
        with s.l: s.d = json.load(open(s.f))
        print(""Reloaded:"", s.d)

    def get(s):
        with s.l: return s.d

class Watch(FileSystemEventHandler):
    def __init__(s,c): s.c, s.p = c, os.path.abspath(c.f)
    def on_modified(s,e):
        if os.path.abspath(e.src_path)==s.p: s.c.load()

# ---------- INPUT ----------
CFG_FILE = ""config.json""
cfg = Config(CFG_FILE)
stop = threading.Event()

def shutdown(sig, frm): stop.set()
signal.signal(signal.SIGINT, shutdown)

obs = Observer()
obs.schedule(Watch(cfg), ""."", False)
obs.start()

# ---------- OUTPUT ----------
try:
    while not stop.is_set():
        print(""Current:"", cfg.get())
        time.sleep(3)
finally:
    obs.stop(); obs.join()
    print(""Stopped"")
",1,GPT,Write a Python program to create a dynamic configuration manager that reloads settings at runtime. MAKE THE CODE MORE SHORTER AND EFFECTIVE TO PASS ALL THE TEST CASES,PYTHON
,"# Importing the NumPy library
import numpy as np

# Calculating the natural logarithm of 1e-50 and 2.5e-50
l1 = np.log(1e-50)
l2 = np.log(2.5e-50)

# Displaying the logarithm of the sum of exponentiations
print(""Logarithm of the sum of exponentiations:"")
print(np.logaddexp(l1, l2))

# Displaying the logarithm of the sum of exponentiations of the inputs in base-2
print(""Logarithm of the sum of exponentiations of the inputs in base-2:"")
print(np.logaddexp2(l1, l2)) 
",0,W3RESOURCE,NA,PYTHON
,"import ast, math

SAFE = {k:v for k,v in vars(math).items() if not k.startswith(""_"")}

def evaluate(expr):
    try:
        return eval(compile(ast.parse(expr, ""eval""), """", ""eval""), {}, SAFE)
    except Exception as e:
        return f""Error: {e}""

# ---------- USER INPUT ----------
expr = input(""Enter math expression: "")

# ---------- OUTPUT ----------
print(""Result:"", evaluate(expr))
",1,GPT,"# Import the Abstract Syntax Tree (AST) module
import ast

# Import the math module for mathematical functions and constants
import math

# Define a class for evaluating mathematical expressions
class MathExpressionEvaluator:
    def __init__(self):
        pass

    # Method to evaluate mathematical expressions
    def evaluate(self, expression):
        try:
            # Parse the expression into an Abstract Syntax Tree (AST)
            parsed_expression = ast.parse(expression, mode='eval')

            # Define the allowed names (functions and constants) for evaluation
            allowed_names = {
                'sin': math.sin,
                'cos': math.cos,
                'tan': math.tan,
                'log': math.log,
                'sqrt': math.sqrt,
                **vars(math)  # Include all functions and constants from the math module
            }

            # Evaluate the AST using a custom namespace that includes the allowed names
            result = eval(compile(parsed_expression, filename='', mode='eval'), {}, allowed_names)
            return result
        except SyntaxError:
            print(""Invalid expression syntax."")
            return None
        except Exception as e:
            print(""Error:"", e)
            return None

# Example usage
if __name__ == ""__main__"":
    evaluator = MathExpressionEvaluator()

    # Evaluate mathematical expressions
    print(""Evaluation Results:"")
    print(""10 + 12 * 4 ="", evaluator.evaluate(""10 + 12 * 4""))
    print(""(12 + 13) * 4 ="", evaluator.evaluate(""(12 + 13) * 4""))
    print(""sin(0.5) ="", evaluator.evaluate(""sin(0.5)""))
    print(""log(10) ="", evaluator.evaluate(""log(10)""))

Write a Python library for parsing and evaluating mathematical expressions., THE ABOVE code is the solution i got from one of the websites make this shorter and give me the effective one with a feature of user entering the inputs ",PYTHON
,"# Importing the NumPy library
import numpy as np

# Creating an array from 0 to 9
x = np.arange(10)

# Displaying the original array
print(""Original array:"")
print(x)

# Performing element-wise division of the array by 3 using true_divide function
print(""Division of the array inputs, element-wise:"")
print(np.true_divide(x, 3)) ",0,W3RESOURCE,NA,PYTHON
,"from collections import OrderedDict

class LRUCache:
    def __init__(self, cap):
        self.cap, self.d = cap, OrderedDict()

    def get(self, k):
        if k not in self.d: return -1
        self.d.move_to_end(k)
        return self.d[k]

    def put(self, k, v):
        if k in self.d: self.d.move_to_end(k)
        self.d[k] = v
        if len(self.d) > self.cap:
            self.d.popitem(last=False)
",1,GPT,Write a Python program to create a caching system with support for LRU eviction policy TO PASS ALL THE TEST CASES,PYTHON
,"import numpy as np
x = [1., 2., 3., 4.]
print(""Original array:"")
print(x)
print(""Largest integer smaller or equal to the division of the inputs:"")
print(np.floor_divide(x, 1.5))
",0,W3RESOURCE,NA,PYTHON
,"import asyncio

class Scheduler:
    def __init__(self): self.tasks=[]
    def add(self, coro, *args): self.tasks.append(coro(*args))
    async def run(self): await asyncio.gather(*self.tasks)

async def task(name, t):
    print(f""Task {name} started ({t}s)"")
    await asyncio.sleep(t)
    print(f""Task {name} finished"")

# ---------- INPUT ----------
async def main():
    s = Scheduler()
    s.add(task, ""A"", 2)
    s.add(task, ""B"", 1)
    s.add(task, ""C"", 3)
    await s.run()

# ---------- OUTPUT ----------
asyncio.run(main())
",1,GPT,Write a Python program that builds a concurrent task scheduler using asyncio WITH I/O,PYTHON
,"# Importing the NumPy library
import numpy as np

# Creating an array from 0 to 6
x = np.arange(7)

# Displaying the original array
print(""Original array:"")
print(x)

# Raising the elements of the array to the power of 3 and displaying the result
print(""First array elements raised to powers from second array, element-wise:"")
print(np.power(x, 3)) ",0,W3RESOURCE,NA,PYTHON
,"import hashlib

class Bloom:
    def __init__(s,n,k):
        s.n,s.k,s.b=n,k,[0]*n

    def _h(s,x):
        h1=int(hashlib.sha256(x.encode()).hexdigest(),16)
        h2=int(hashlib.md5(x.encode()).hexdigest(),16)
        return [(h1+i*h2)%s.n for i in range(s.k)]

    def add(s,x):
        for i in s._h(x): s.b[i]=1

    def check(s,x):
        return all(s.b[i] for i in s._h(x))
",1,GPT,"WRITE THE PYTHON CODE FOR Bloom Filter Implementation with i/o , let the code you provide be efficient and accurate for the results it provide",PYTHON
,"def binary_search(item_list,item):
	first = 0
	last = len(item_list)-1
	found = False
	while( first<=last and not found):
		mid = (first + last)//2
		if item_list[mid] == item :
			found = True
		else:
			if item < item_list[mid]:
				last = mid - 1
			else:
				first = mid + 1	
	return found
	
print(binary_search([1,2,3,5,8], 6))
print(binary_search([1,2,3,5,8], 5))",0,W3RESOURCE,NA,PYTHON
,"import json

class Address:
    def __init__(s,st,ct,stt,z): s.street, s.city, s.state, s.zip = st,ct,stt,z

class Person:
    def __init__(s,n,a,ad): s.name, s.age, s.address = n,a,ad

class Encoder(json.JSONEncoder):
    def default(s,o):
        if hasattr(o,""__dict__""):
            return {""__t__"":o.__class__.__name__, **o.__dict__}
        return super().default(o)

def decoder(d):
    if ""__t__"" in d:
        cls = {""Address"":Address,""Person"":Person}[d.pop(""__t__"")]
        return cls(**d)
    return d
",1,GPT,GIVE me a python code for Custom JSON Encoder/Decoder,PYTHON
,"def Sequential_Search(dlist, item):

    pos = 0
    found = False
    
    while pos < len(dlist) and not found:
        if dlist[pos] == item:
            found = True
        else:
            pos = pos + 1
    
    return found, pos

print(Sequential_Search([11,23,58,31,56,77,43,12,65,19],31))",0,W3RESOURCE,NA,PYTHON
,"import os, shutil, argparse

def sync(src, dst):
    if not os.path.isdir(src) or not os.path.isdir(dst):
        print(""Invalid source or destination""); return
    for r,_,fs in os.walk(src):
        d = os.path.join(dst, os.path.relpath(r, src))
        os.makedirs(d, exist_ok=True)
        for f in fs:
            shutil.copy2(os.path.join(r,f), os.path.join(d,f))

if __name__ == ""__main__"":
    p = argparse.ArgumentParser()
    p.add_argument(""src""); p.add_argument(""dst"")
    a = p.parse_args()
    sync(a.src, a.dst)
    print(""Sync complete"")
",1,GPT,"GIVE ME A python CODE FOR Command-Line File Synchronizer , make it more shorter for effective to pass all the testcases",PYTHON
,"def Ordered_binary_Search(olist, item):
    
    if len(olist) == 0:
        return False
    else:
        midpoint = len(olist) // 2
        if olist[midpoint] == item:
            return True
        else:
            if item < olist[midpoint]:
                return binarySearch(olist[:midpoint], item)
            else:
                return binarySearch(olist[midpoint+1:], item)

def binarySearch(alist, item):

    first = 0
    last = len(alist) - 1
    found = False

    while first <= last and not found:
        midpoint = (first + last) // 2
        if alist[midpoint] == item:
            found = True
        else:
            if item < alist[midpoint]:
                last = midpoint - 1
            else:
                first = midpoint + 1

    return found

print(Ordered_binary_Search([0, 1, 3, 8, 14, 18, 19, 34, 52], 3))
print(Ordered_binary_Search([0, 1, 3, 8, 14, 18, 19, 34, 52], 17))",0,W3RESOURCE,NA,PYTHON
,"import heapq

def astar(start, goal, g, h):
    pq = [(h(start), 0, start, [start])]
    seen = set()
    while pq:
        f,c,u,p = heapq.heappop(pq)
        if u == goal: return p, c
        if u in seen: continue
        seen.add(u)
        for v,w in g[u]:
            heapq.heappush(pq,(c+w+h(v), c+w, v, p+[v]))

# ---------- INPUT ----------
graph = {
    'A':[('B',1),('C',3)],
    'B':[('D',1),('E',4)],
    'C':[('F',5)],
    'D':[('G',1)],
    'E':[('G',1)],
    'F':[('G',1)],
    'G':[]
}
heuristic = {'A':5,'B':4,'C':4,'D':2,'E':2,'F':3,'G':0}

path, cost = astar('A','G',graph,lambda n: heuristic[n])

# ---------- OUTPUT ----------
print(""Path:"", path)
print(""Cost:"", cost)
",1,GPT,give me the code for A* Search Algorithm in  shorter lines to implement it with i/o,PYTHON
,"def bubbleSort(nlist):
    for passnum in range(len(nlist)-1,0,-1):
        for i in range(passnum):
            if nlist[i]>nlist[i+1]:
                temp = nlist[i]
                nlist[i] = nlist[i+1]
                nlist[i+1] = temp

nlist = [14,46,43,27,57,41,45,21,70]
bubbleSort(nlist)
print(nlist)",0,W3RESOURCE,NA,PYTHON
,"from dataclasses import dataclass, field, fields

class ValidationError(Exception): pass

def vfield(d=None, v=()):
    return field(default=d, metadata={""v"": v})

def validate(o):
    for f in fields(o):
        for fn in f.metadata.get(""v"", ()):
            if not fn(getattr(o, f.name)):
                raise ValidationError(f""{f.name} invalid"")

@dataclass
class User:
    name: str
    age: int = vfield(0, v=[lambda x: 0 <= x <= 150])
    email: str = vfield("""", v=[lambda x: ""@"" in x])

# ---------- INPUT ----------
u = User(""Arsen"", 30, ""arsen@example.com"")

# ---------- OUTPUT ----------
try:
    validate(u)
    print(""User is valid"")
except ValidationError as e:
    print(e)
",1,GPT,write a shorter python code for Data Validation Library with Dataclasses including I/O,PYTHON
,"def selectionSort(nlist):
   for fillslot in range(len(nlist)-1,0,-1):
       maxpos=0
       for location in range(1,fillslot+1):
           if nlist[location]>nlist[maxpos]:
               maxpos = location

       temp = nlist[fillslot]
       nlist[fillslot] = nlist[maxpos]
       nlist[maxpos] = temp

nlist = [14,46,43,27,57,41,45,21,70]
selectionSort(nlist)
print(nlist)
",0,W3RESOURCE,NA,PYTHON
,"from queue import PriorityQueue
from threading import Thread

q = PriorityQueue()

def producer():
    for _ in range(int(input(""Items: ""))):
        x,p = map(int,input(""item priority: "").split())
        q.put((p,x))
    q.put((None,None))

def consumer():
    while (p,x := q.get()) != (None,None):
        print(""Consumed:"", x)

Thread(target=producer).start()
Thread(target=consumer).start()
",1,GPT,"# Import the queue module to use PriorityQueue import queue # Import the threading module to use threads and locks import threading # Define a class for a thread-safe priority queue class ThreadSafePriorityQueue: def __init__(self): # Initialize a PriorityQueue object to hold the items self._queue = queue.PriorityQueue() # Initialize a lock to ensure thread safety self._lock = threading.Lock() # Method to put an item into the priority queue def put(self, item, priority): # Acquire the lock to ensure thread safety with self._lock: # Put the item into the queue with its priority self._queue.put((priority, item)) # Method to get an item from the priority queue def get(self): # Acquire the lock to ensure thread safety with self._lock: # Check if the queue is not empty if not self._queue.empty(): # Get the item with the highest priority (lowest priority number) priority, item = self._queue.get() # Return the item return item else: # Return None if the queue is empty return None # Example usage to demonstrate the thread-safe priority queue if __name__ == ""__main__"": # Define a producer function to add items to the queue def producer(q): # Add 5 items to the queue with their priority as their value for i in range(5): q.put(i, i) # Define a consumer function to get items from the queue def consumer(q): # Continuously get items from the queue while True: # Get an item from the queue item = q.get() # If the item is None, break the loop (end of processing) if item is None: break # Print the consumed item print(""Consumed:"", item) # Create an instance of the thread-safe priority queue q = ThreadSafePriorityQueue() # Create a producer thread to add items to the queue producer_thread = threading.Thread(target=producer, args=(q,)) # Create a consumer thread to get items from the queue consumer_thread = threading.Thread(target=consumer, args=(q,)) # Start the producer thread producer_thread.start() # Start the consumer thread consumer_thread.start() # Wait for the producer thread to finish producer_thread.join() # Add a sentinel value to the queue to signal the consumer to stop q.put(None, None) # Wait for the consumer thread to finish consumer_thread.join() refer this code and give me the shorter version of this code with minimal lines to implement it efficiently",PYTHON
,"def insertionSort(nlist):
   for index in range(1,len(nlist)):

     currentvalue = nlist[index]
     position = index

     while position>0 and nlist[position-1]>currentvalue:
         nlist[position]=nlist[position-1]
         position = position-1

     nlist[position]=currentvalue

nlist = [14,46,43,27,57,41,45,21,70]
insertionSort(nlist)
print(nlist)",0,W3RESOURCE,NA,PYTHON
,"def matmul(A, B):
    return [[sum(a*b for a,b in zip(r,c)) for c in zip(*B)] for r in A]

r1,c1 = map(int,input(""A rows cols: "").split())
A = [list(map(int,input().split())) for _ in range(r1)]

r2,c2 = map(int,input(""B rows cols: "").split())
B = [list(map(int,input().split())) for _ in range(r2)]

print(matmul(A,B))
",1,GPT,give me a pythoncode for Matrix Multiplication via List Comprehensions also add a way to give input and get the result of the matrix multiplication within a shorter lines of code,PYTHON
,"def shellSort(alist):
    sublistcount = len(alist)//2
    while sublistcount > 0:
      for start_position in range(sublistcount):
        gap_InsertionSort(alist, start_position, sublistcount)

      print(""After increments of size"",sublistcount, ""The list is"",nlist)

      sublistcount = sublistcount // 2

def gap_InsertionSort(nlist,start,gap):
    for i in range(start+gap,len(nlist),gap):

        current_value = nlist[i]
        position = i

        while position>=gap and nlist[position-gap]>current_value:
            nlist[position]=nlist[position-gap]
            position = position-gap

        nlist[position]=current_value


nlist = [14,46,43,27,57,41,45,21,70]
shellSort(nlist)
print(nlist)
",0,W3RESOURCE,NA,PYTHON
,"class Node:
    def __init__(self, v, kids=None):
        self.v, self.kids = v, kids or []

    def __iter__(self):
        stack = [self]
        while stack:
            n = stack.pop()
            yield n.v
            stack.extend(reversed(n.kids))
",1,GPT,give me the shorter lines of python code for Custom Tree Iterator,PYTHON
,"def mergeSort(nlist):
    print(""Splitting "",nlist)
    if len(nlist)>1:
        mid = len(nlist)//2
        lefthalf = nlist[:mid]
        righthalf = nlist[mid:]

        mergeSort(lefthalf)
        mergeSort(righthalf)
        i=j=k=0       
        while i < len(lefthalf) and j < len(righthalf):
            if lefthalf[i] < righthalf[j]:
                nlist[k]=lefthalf[i]
                i=i+1
            else:
                nlist[k]=righthalf[j]
                j=j+1
            k=k+1

        while i < len(lefthalf):
            nlist[k]=lefthalf[i]
            i=i+1
            k=k+1

        while j < len(righthalf):
            nlist[k]=righthalf[j]
            j=j+1
            k=k+1
    print(""Merging "",nlist)

nlist = [14,46,43,27,57,41,45,21,70]
mergeSort(nlist)
print(nlist)
",0,W3RESOURCE,NA,PYTHON
,"import time

class Timer:
    def __init__(self, func):
        self.func = func

    def __get__(self, obj, objtype=None):
        return lambda *a, **k: self(obj, *a, **k)

    def __call__(self, obj, *a, **k):
        t = time.time()
        r = self.func(obj, *a, **k)
        print(f""{self.func.__name__}: {time.time()-t:.4f}s"")
        return r
",1,GPT,"write a python code for Class-Based Decorator for Execution Time , let the code be more shorter .",PYTHON
,"def quickSort(data_list):
   quickSortHlp(data_list,0,len(data_list)-1)

def quickSortHlp(data_list,first,last):
   if first < last:

       splitpoint = partition(data_list,first,last)

       quickSortHlp(data_list,first,splitpoint-1)
       quickSortHlp(data_list,splitpoint+1,last)


def partition(data_list,first,last):
   pivotvalue = data_list[first]

   leftmark = first+1
   rightmark = last

   done = False
   while not done:

       while leftmark <= rightmark and data_list[leftmark] <= pivotvalue:
           leftmark = leftmark + 1

       while data_list[rightmark] >= pivotvalue and rightmark >= leftmark:
           rightmark = rightmark -1

       if rightmark < leftmark:
           done = True
       else:
           temp = data_list[leftmark]
           data_list[leftmark] = data_list[rightmark]
           data_list[rightmark] = temp

   temp = data_list[first]
   data_list[first] = data_list[rightmark]
   data_list[rightmark] = temp


   return rightmark

data_list = [54,26,93,17,77,31,44,55,20]
quickSort(data_list)
print(data_list)",0,W3RESOURCE,NA,PYTHON
,"import requests
from bs4 import BeautifulSoup
from concurrent.futures import ThreadPoolExecutor
from urllib.parse import urljoin

def fetch(url):
    try:
        return BeautifulSoup(requests.get(url, timeout=5).text, ""html.parser"")
    except:
        return None

def scrape(urls, workers=10):
    with ThreadPoolExecutor(workers) as t:
        return [s for s in t.map(fetch, urls) if s]

start = ""https://example.com""
soup = fetch(start)

links = {urljoin(start, a[""href""]) for a in soup.select(""a[href]"")}
pages = scrape(links)

for p in pages:
    print(p.title.string if p.title else ""No title"")
",1,GPT,give me the python3 code for multithread webscrapper in an more efficient way with shorter lines of code to implement ,PYTHON
,"def counting_sort(array1, max_val):
    m = max_val + 1
    count = [0] * m                
    
    for a in array1:
    # count occurences
        count[a] += 1             
    i = 0
    for a in range(m):            
        for c in range(count[a]):  
            array1[i] = a
            i += 1
    return array1

print(counting_sort( [1, 2, 7, 3, 2, 1, 4, 2, 3, 2, 1], 7 ))",0,GFG,NA,PYTHON
,"def maxProfit(prices):
    min_price = float('inf')
    max_profit = 0

    for price in prices:
        min_price = min(min_price, price)
        max_profit = max(max_profit, price - min_price)

    return max_profit
",1,GPT,"You are given an array prices where prices[i] is the price of a stock on day i.
You may choose one day to buy and a later day to sell.
Return the maximum profit you can achieve. If no profit is possible, return 0.

Provide:
- An optimal O(n) solution
- Explanation of the approach
- Python implementation",PYTHON
,"class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        maxP = 0
        minBuy = prices[0]

        for sell in prices:
            maxP = max(maxP, sell - minBuy)
            minBuy = min(minBuy, sell)
        return maxP",0,GFG,NA,PYTHON
,"from collections import Counter

def topKFrequent(nums, k):
    count = Counter(nums)
    buckets = [[] for _ in range(len(nums) + 1)]

    for num, freq in count.items():
        buckets[freq].append(num)

    res = []
    for i in range(len(buckets) - 1, 0, -1):
        for num in buckets[i]:
            res.append(num)
            if len(res) == k:
                return res
",1,GPT,"Given an integer array nums and an integer k, return the k most frequent elements.
The solution must be better than O(n log n).

Provide:
- Optimal approach
- Python code using efficient data structures",PYTHON
,"class Solution:
    def topKFrequent(self, nums: List[int], k: int) -> List[int]:
        count = {}
        freq = [[] for i in range(len(nums) + 1)]

        for num in nums:
            count[num] = 1 + count.get(num, 0)
        for num, cnt in count.items():
            freq[cnt].append(num)

        res = []
        for i in range(len(freq) - 1, 0, -1):
            for num in freq[i]:
                res.append(num)
                if len(res) == k:
                    return res",0,GFG,NA,PYTHON
,"def longestConsecutive(nums):
    num_set = set(nums)
    longest = 0

    for num in num_set:
        if num - 1 not in num_set:
            length = 1
            while num + length in num_set:
                length += 1
            longest = max(longest, length)

    return longest
",1,GPT,"Given an unsorted array of integers nums, return the length of the longest consecutive elements sequence.
The solution must run in O(n) time.",PYTHON
,"class Solution:
    def longestConsecutive(self, nums: List[int]) -> int:
        mp = defaultdict(int)
        res = 0

        for num in nums:
            if not mp[num]:
                mp[num] = mp[num - 1] + mp[num + 1] + 1
                mp[num - mp[num - 1]] = mp[num]
                mp[num + mp[num + 1]] = mp[num]
                res = max(res, mp[num])
        return res",0,GFG,NA,PYTHON
,"def twoSum(numbers, target):
    l, r = 0, len(numbers) - 1

    while l < r:
        s = numbers[l] + numbers[r]
        if s == target:
            return [l + 1, r + 1]
        elif s < target:
            l += 1
        else:
            r -= 1
",1,GPT,"Given a sorted array of integers and a target,
return the 1-based indices of the two numbers such that they add up to the target.
Use only constant extra space.",PYTHON
,"class Solution:
    def twoSum(self, numbers: List[int], target: int) -> List[int]:
        l, r = 0, len(numbers) - 1

        while l < r:
            curSum = numbers[l] + numbers[r]

            if curSum > target:
                r -= 1
            elif curSum < target:
                l += 1
            else:
                return [l + 1, r + 1]
        return []",0,GFG,NA,PYTHON
,"def maxArea(height):
    l, r = 0, len(height) - 1
    res = 0

    while l < r:
        res = max(res, min(height[l], height[r]) * (r - l))
        if height[l] < height[r]:
            l += 1
        else:
            r -= 1

    return res
",1,GPT,"Given an array height, find two lines that together with the x-axis form a container,
such that the container contains the most water.",PYTHON
,"class Solution:
    def maxArea(self, heights: List[int]) -> int:
        l, r = 0, len(heights) - 1
        res = 0

        while l < r:
            area = min(heights[l], heights[r]) * (r - l)
            res = max(res, area)
            if heights[l] <= heights[r]:
                l += 1
            else:
                r -= 1
        return res",0,GFG,NA,PYTHON
,"def trap(height):
    l, r = 0, len(height) - 1
    left_max = right_max = 0
    res = 0

    while l < r:
        if height[l] < height[r]:
            left_max = max(left_max, height[l])
            res += left_max - height[l]
            l += 1
        else:
            right_max = max(right_max, height[r])
            res += right_max - height[r]
            r -= 1

    return res
",1,GPT,"Given an array height representing elevation map,
compute how much water it can trap after raining.",PYTHON
,"class Solution:
    def trap(self, height: List[int]) -> int:
        if not height:
            return 0

        l, r = 0, len(height) - 1
        leftMax, rightMax = height[l], height[r]
        res = 0
        while l < r:
            if leftMax < rightMax:
                l += 1
                leftMax = max(leftMax, height[l])
                res += leftMax - height[l]
            else:
                r -= 1
                rightMax = max(rightMax, height[r])
                res += rightMax - height[r]
        return res",0,GFG,NA,PYTHON
,"from collections import Counter

def checkInclusion(s1, s2):
    if len(s1) > len(s2):
        return False

    s1_count = Counter(s1)
    window = Counter(s2[:len(s1)])

    if s1_count == window:
        return True

    for i in range(len(s1), len(s2)):
        window[s2[i]] += 1
        window[s2[i - len(s1)]] -= 1
        if window[s2[i - len(s1)]] == 0:
            del window[s2[i - len(s1)]]
        if window == s1_count:
            return True

    return False
",1,GPT,"Given two strings s1 and s2, return true if s2 contains a permutation of s1.
Use a sliding window approach.",PYTHON
,"class Solution:
    def checkInclusion(self, s1: str, s2: str) -> bool:
        if len(s1) > len(s2):
            return False

        s1Count, s2Count = [0] * 26, [0] * 26
        for i in range(len(s1)):
            s1Count[ord(s1[i]) - ord('a')] += 1
            s2Count[ord(s2[i]) - ord('a')] += 1

        matches = 0
        for i in range(26):
            matches += (1 if s1Count[i] == s2Count[i] else 0)

        l = 0
        for r in range(len(s1), len(s2)):
            if matches == 26:
                return True

            index = ord(s2[r]) - ord('a')
            s2Count[index] += 1
            if s1Count[index] == s2Count[index]:
                matches += 1
            elif s1Count[index] + 1 == s2Count[index]:
                matches -= 1

            index = ord(s2[l]) - ord('a')
            s2Count[index] -= 1
            if s1Count[index] == s2Count[index]:
                matches += 1
            elif s1Count[index] - 1 == s2Count[index]:
                matches -= 1
            l += 1
        return matches == 26",0,GFG,NA,PYTHON
,"from collections import Counter

def minWindow(s, t):
    if not t or not s:
        return """"

    t_count = Counter(t)
    window = {}
    have, need = 0, len(t_count)
    res, res_len = [-1, -1], float('inf')
    l = 0

    for r in range(len(s)):
        c = s[r]
        window[c] = window.get(c, 0) + 1

        if c in t_count and window[c] == t_count[c]:
            have += 1

        while have == need:
            if (r - l + 1) < res_len:
                res = [l, r]
                res_len = r - l + 1

            window[s[l]] -= 1
            if s[l] in t_count and window[s[l]] < t_count[s[l]]:
                have -= 1
            l += 1

    l, r = res
    return s[l:r+1] if res_len != float('inf') else """"
",1,GPT,"Given strings s and t, return the minimum window in s which contains all characters of t.
If no such window exists, return an empty string.",PYTHON
,"class Solution:
    def minWindow(self, s: str, t: str) -> str:
        if t == """":
            return """"

        countT, window = {}, {}
        for c in t:
            countT[c] = 1 + countT.get(c, 0)

        have, need = 0, len(countT)
        res, resLen = [-1, -1], float(""infinity"")
        l = 0
        for r in range(len(s)):
            c = s[r]
            window[c] = 1 + window.get(c, 0)

            if c in countT and window[c] == countT[c]:
                have += 1

            while have == need:
                if (r - l + 1) < resLen:
                    res = [l, r]
                    resLen = r - l + 1

                window[s[l]] -= 1
                if s[l] in countT and window[s[l]] < countT[s[l]]:
                    have -= 1
                l += 1
        l, r = res
        return s[l : r + 1] if resLen != float(""infinity"") else """"",0,GFG,NA,PYTHON
,"def dailyTemperatures(temperatures):
    res = [0] * len(temperatures)
    stack = []

    for i, temp in enumerate(temperatures):
        while stack and temp > stack[-1][0]:
            stack_temp, idx = stack.pop()
            res[idx] = i - idx
        stack.append((temp, i))

    return res
",1,GPT,"Given an array temperatures, return an array such that each index shows
how many days until a warmer temperature.
Use a monotonic stack.",PYTHON
,"class Solution:
    def dailyTemperatures(self, temperatures: List[int]) -> List[int]:
        n = len(temperatures)
        res = [0] * n

        for i in range(n - 2, -1, -1):
            j = i + 1
            while j < n and temperatures[j] <= temperatures[i]:
                if res[j] == 0:
                    j = n
                    break
                j += res[j]

            if j < n:
                res[i] = j - i
        return res",0,GFG,NA,PYTHON
,"def carFleet(target, position, speed):
    cars = sorted(zip(position, speed), reverse=True)
    stack = []

    for pos, spd in cars:
        time = (target - pos) / spd
        if not stack or time > stack[-1]:
            stack.append(time)

    return len(stack)
",1,GPT,"Given target, position, and speed arrays,
return the number of car fleets that will arrive at the destination.",PYTHON
,"class Solution:
    def carFleet(self, target: int, position: List[int], speed: List[int]) -> int:
        pair = [(p, s) for p, s in zip(position, speed)]
        pair.sort(reverse=True)

        fleets = 1
        prevTime = (target - pair[0][0]) / pair[0][1]
        for i in range(1, len(pair)):
            currCar = pair[i]
            currTime = (target - currCar[0]) / currCar[1]
            if currTime > prevTime:
                fleets += 1
                prevTime = currTime
        return fleets",0,GFG,NA,PYTHON
,"import math

def minEatingSpeed(piles, h):
    l, r = 1, max(piles)

    while l < r:
        m = (l + r) // 2
        hours = sum(math.ceil(p / m) for p in piles)
        if hours <= h:
            r = m
        else:
            l = m + 1

    return l
",1,GPT,"Given an array piles where piles[i] is the number of bananas in the ith pile,
and an integer h representing hours,
find the minimum integer eating speed k such that Koko can eat all bananas within h hours.",PYTHON
,"class Solution:
    def minEatingSpeed(self, piles: List[int], h: int) -> int:
        l, r = 1, max(piles)
        res = r

        while l <= r:
            k = (l + r) // 2

            totalTime = 0
            for p in piles:
                totalTime += math.ceil(float(p) / k)
            if totalTime <= h:
                res = k
                r = k - 1
            else:
                l = k + 1
        return res",0,GFG,NA,PYTHON
,"def searchMatrix(matrix, target):
    if not matrix or not matrix[0]:
        return False

    rows, cols = len(matrix), len(matrix[0])
    l, r = 0, rows * cols - 1

    while l <= r:
        m = (l + r) // 2
        val = matrix[m // cols][m % cols]
        if val == target:
            return True
        elif val < target:
            l = m + 1
        else:
            r = m - 1

    return False
",1,GPT,"Solve the problem ""Search a 2D Matrix"".

The matrix has the following properties:
- Integers in each row are sorted
- First integer of each row is greater than the last integer of the previous row

Given a target, return true if found.

Provide O(log(m*n)) Python solution.
",PYTHON
,"class Solution:
    def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
        ROWS, COLS = len(matrix), len(matrix[0])

        l, r = 0, ROWS * COLS - 1
        while l <= r:
            m = l + (r - l) // 2
            row, col = m // COLS, m % COLS
            if target > matrix[row][col]:
                l = m + 1
            elif target < matrix[row][col]:
                r = m - 1
            else:
                return True
        return False",0,GFG,NA,PYTHON
,"def findMedianSortedArrays(nums1, nums2):
    A, B = nums1, nums2
    if len(A) > len(B):
        A, B = B, A

    total = len(A) + len(B)
    half = total // 2
    l, r = 0, len(A)

    while True:
        i = (l + r) // 2
        j = half - i

        Aleft = A[i - 1] if i > 0 else float('-inf')
        Aright = A[i] if i < len(A) else float('inf')
        Bleft = B[j - 1] if j > 0 else float('-inf')
        Bright = B[j] if j < len(B) else float('inf')

        if Aleft <= Bright and Bleft <= Aright:
            if total % 2:
                return min(Aright, Bright)
            return (max(Aleft, Bleft) + min(Aright, Bright)) / 2
        elif Aleft > Bright:
            r = i - 1
        else:
            l = i + 1
",1,GPT,"Solve the problem ""Median of Two Sorted Arrays"".

Given two sorted arrays nums1 and nums2,
return the median of the two sorted arrays.
The overall time complexity must be O(log(min(n, m))).",PYTHON
,"class Solution:
    def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float:
        A, B = nums1, nums2
        total = len(nums1) + len(nums2)
        half = total // 2

        if len(B) < len(A):
            A, B = B, A

        l, r = 0, len(A) - 1
        while True:
            i = (l + r) // 2
            j = half - i - 2

            Aleft = A[i] if i >= 0 else float(""-infinity"")
            Aright = A[i + 1] if (i + 1) < len(A) else float(""infinity"")
            Bleft = B[j] if j >= 0 else float(""-infinity"")
            Bright = B[j + 1] if (j + 1) < len(B) else float(""infinity"")

            if Aleft <= Bright and Bleft <= Aright:
                if total % 2:
                    return min(Aright, Bright)
                return (max(Aleft, Bleft) + min(Aright, Bright)) / 2
            elif Aleft > Bright:
                r = i - 1
            else:
                l = i + 1",0,GFG,NA,PYTHON
,"def reverseList(head):
    prev = None
    curr = head

    while curr:
        nxt = curr.next
        curr.next = prev
        prev = curr
        curr = nxt

    return prev
",1,GPT,"Solve the problem ""Reverse a Linked List"".

Given the head of a singly linked list,
reverse the list and return the new head.",PYTHON
,"# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next

class Solution:
    def reverseList(self, head: ListNode) -> ListNode:
        prev, curr = None, head

        while curr:
            temp = curr.next
            curr.next = prev
            prev = curr
            curr = temp
        return prev",0,GFG,NA,PYTHON
,"def reorderList(head):
    if not head:
        return

    slow, fast = head, head
    while fast and fast.next:
        slow = slow.next
        fast = fast.next.next

    prev, curr = None, slow.next
    slow.next = None

    while curr:
        nxt = curr.next
        curr.next = prev
        prev = curr
        curr = nxt

    first, second = head, prev
    while second:
        tmp1, tmp2 = first.next, second.next
        first.next = second
        second.next = tmp1
        first, second = tmp1, tmp2
",1,GPT,"Solve the problem ""Reorder Linked List"".

Reorder the list as:
L0 → Ln → L1 → Ln-1 → L2 → Ln-2 → …

Do it in-place with O(1) extra space.
",PYTHON
,"# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next

class Solution:
    def reorderList(self, head: Optional[ListNode]) -> None:
        slow, fast = head, head.next
        while fast and fast.next:
            slow = slow.next
            fast = fast.next.next

        second = slow.next
        prev = slow.next = None
        while second:
            tmp = second.next
            second.next = prev
            prev = second
            second = tmp

        first, second = head, prev
        while second:
            tmp1, tmp2 = first.next, second.next
            first.next = second
            second.next = tmp1
            first, second = tmp1, tmp2",0,GFG,NA,PYTHON
,"def findDuplicate(nums):
    slow = fast = nums[0]

    while True:
        slow = nums[slow]
        fast = nums[nums[fast]]
        if slow == fast:
            break

    slow = nums[0]
    while slow != fast:
        slow = nums[slow]
        fast = nums[fast]

    return slow
",1,GPT,"Solve the problem ""Find the Duplicate Number"".

Given an array nums containing n+1 integers where each integer is in the range [1, n],
return the duplicate number without modifying the array
and using constant extra space.

Provide Python solution using cycle detection.
",PYTHON
,"class Solution:
    def findDuplicate(self, nums: List[int]) -> int:
        slow, fast = 0, 0
        while True:
            slow = nums[slow]
            fast = nums[nums[fast]]
            if slow == fast:
                break

        slow2 = 0
        while True:
            slow = nums[slow]
            slow2 = nums[slow2]
            if slow == slow2:
                return slow",0,GFG,NA,PYTHON
,"def mergeTwoLists(l1, l2):
    dummy = curr = ListNode(0)

    while l1 and l2:
        if l1.val < l2.val:
            curr.next = l1
            l1 = l1.next
        else:
            curr.next = l2
            l2 = l2.next
        curr = curr.next

    curr.next = l1 or l2
    return dummy.next
",1,GPT,"Solve the problem ""Merge Two Sorted Linked Lists"".

Given two sorted linked lists,
merge them into one sorted list and return its head.",PYTHON
,"# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next

class Solution:
    def mergeTwoLists(self, list1: ListNode, list2: ListNode) -> ListNode:
        dummy = node = ListNode()

        while list1 and list2:
            if list1.val < list2.val:
                node.next = list1
                list1 = list1.next
            else:
                node.next = list2
                list2 = list2.next
            node = node.next

        node.next = list1 or list2

        return dummy.next",0,GFG,NA,PYTHON
,"def reverseKGroup(head, k):
    dummy = ListNode(0)
    dummy.next = head
    prev = dummy

    while True:
        kth = prev
        for _ in range(k):
            kth = kth.next
            if not kth:
                return dummy.next

        nxt = kth.next
        curr = prev.next

        for _ in range(k):
            tmp = curr.next
            curr.next = nxt
            nxt = curr
            curr = tmp

        tmp = prev.next
        prev.next = kth
        prev = tmp
",1,GPT,"Solve the problem ""Reverse Nodes in K-Group"".

Given a linked list, reverse the nodes of the list k at a time.
If the number of nodes is not a multiple of k, leave them as is.

Provide Python solution.
",PYTHON
,"# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next

class Solution:
    def reverseKGroup(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
        dummy = ListNode(0, head)
        groupPrev = dummy

        while True:
            kth = self.getKth(groupPrev, k)
            if not kth:
                break
            groupNext = kth.next

            prev, curr = kth.next, groupPrev.next
            while curr != groupNext:
                tmp = curr.next
                curr.next = prev
                prev = curr
                curr = tmp

            tmp = groupPrev.next
            groupPrev.next = kth
            groupPrev = tmp
        return dummy.next

    def getKth(self, curr, k):
        while curr and k > 0:
            curr = curr.next
            k -= 1
        return curr",0,GFG,NA,PYTHON
,"def invertTree(root):
    if not root:
        return None

    root.left, root.right = invertTree(root.right), invertTree(root.left)
    return root
",1,GPT,"Solve the problem ""Invert Binary Tree"".

Given the root of a binary tree,
invert the tree and return its root.

Provide Python solution.
",PYTHON
,"# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right

class Solution:
    def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
        if not root:
            return None
        stack = [root]
        while stack:
            node = stack.pop()
            node.left, node.right = node.right, node.left
            if node.left:
                stack.append(node.left)
            if node.right:
                stack.append(node.right)
        return root",0,GFG,NA,PYTHON
,"def isBalanced(root):
    def dfs(node):
        if not node:
            return 0

        left = dfs(node.left)
        if left == -1:
            return -1
        right = dfs(node.right)
        if right == -1:
            return -1

        if abs(left - right) > 1:
            return -1

        return 1 + max(left, right)

    return dfs(root) != -1
",1,GPT,"Solve the problem ""Balanced Binary Tree"".

Given a binary tree,
determine if it is height-balanced.

Provide Python solution.
",PYTHON
,"# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right

class Solution:
    def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
        if not root:
            return None
        stack = [root]
        while stack:
            node = stack.pop()
            node.left, node.right = node.right, node.left
            if node.left:
                stack.append(node.left)
            if node.right:
                stack.append(node.right)
        return root",0,GFG,NA,PYTHON
,"def isSubtree(root, subRoot):
    def isSame(a, b):
        if not a and not b:
            return True
        if not a or not b or a.val != b.val:
            return False
        return isSame(a.left, b.left) and isSame(a.right, b.right)

    if not root:
        return False
    if isSame(root, subRoot):
        return True
    return isSubtree(root.left, subRoot) or isSubtree(root.right, subRoot)
",1,GPT,"Solve the problem ""Subtree of Another Tree"".

Given the roots of two binary trees root and subRoot,
return true if there is a subtree of root with the same structure and values as subRoot.

Provide Python solution.
",PYTHON
,"# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right

class Solution:
    def serialize(self, root: Optional[TreeNode]) -> str:
        if root == None:
            return ""$#""

        return (""$"" + str(root.val) + self.serialize(root.left) + self.serialize(root.right))

    def z_function(self, s: str) -> list:
        z = [0] * len(s)
        l, r, n = 0, 0, len(s)
        for i in range(1, n):
            if i <= r:
                z[i] = min(r - i + 1, z[i - l])
            while i + z[i] < n and s[z[i]] == s[i + z[i]]:
                z[i] += 1
            if i + z[i] - 1 > r:
                l, r = i, i + z[i] - 1
        return z

    def isSubtree(self, root: Optional[TreeNode], subRoot: Optional[TreeNode]) -> bool:
        serialized_root = self.serialize(root)
        serialized_subRoot = self.serialize(subRoot)
        combined = serialized_subRoot + ""|"" + serialized_root

        z_values = self.z_function(combined)
        sub_len = len(serialized_subRoot)

        for i in range(sub_len + 1, len(combined)):
            if z_values[i] == sub_len:
                return True
        return False",0,GFG,NA,PYTHON
,"from collections import deque

def levelOrder(root):
    if not root:
        return []

    res = []
    q = deque([root])

    while q:
        level = []
        for _ in range(len(q)):
            node = q.popleft()
            level.append(node.val)
            if node.left:
                q.append(node.left)
            if node.right:
                q.append(node.right)
        res.append(level)

    return res
",1,GPT,"Solve the problem ""Binary Tree Level Order Traversal"".

Given the root of a binary tree,
return the level order traversal of its nodes' values.

Provide Python solution using BFS.
",PYTHON

,"# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right

class Solution:
    def levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
        res = []

        q = collections.deque()
        q.append(root)

        while q:
            qLen = len(q)
            level = []
            for i in range(qLen):
                node = q.popleft()
                if node:
                    level.append(node.val)
                    q.append(node.left)
                    q.append(node.right)
            if level:
                res.append(level)

        return res",0,GFG,NA,PYTHON

,"def exist(board, word):
    rows, cols = len(board), len(board[0])

    def dfs(r, c, i):
        if i == len(word):
            return True
        if r < 0 or c < 0 or r >= rows or c >= cols or board[r][c] != word[i]:
            return False

        tmp = board[r][c]
        board[r][c] = ""#""
        found = (dfs(r+1, c, i+1) or dfs(r-1, c, i+1) or
                 dfs(r, c+1, i+1) or dfs(r, c-1, i+1))
        board[r][c] = tmp
        return found

    for r in range(rows):
        for c in range(cols):
            if dfs(r, c, 0):
                return True
    return False
",1,GPT,"Solve the problem ""Word Search"".

Given a 2D board of characters and a word,
return true if the word exists in the grid.
The word can be constructed from adjacent cells
(horizontal or vertical) without reusing a cell.",PYTHON

,"class Solution:
    def exist(self, board: List[List[str]], word: str) -> bool:
        ROWS, COLS = len(board), len(board[0])

        def dfs(r, c, i):
            if i == len(word):
                return True
            if (r < 0 or c < 0 or r >= ROWS or c >= COLS or
                word[i] != board[r][c] or board[r][c] == '#'):
                return False

            board[r][c] = '#'
            res = (dfs(r + 1, c, i + 1) or
                   dfs(r - 1, c, i + 1) or
                   dfs(r, c + 1, i + 1) or
                   dfs(r, c - 1, i + 1))
            board[r][c] = word[i]
            return res

        for r in range(ROWS):
            for c in range(COLS):
                if dfs(r, c, 0):
                    return True
        return False",0,GFG,NA,PYTHON

,"def letterCombinations(digits):
    if not digits:
        return []

    phone = {
        ""2"": ""abc"", ""3"": ""def"", ""4"": ""ghi"",
        ""5"": ""jkl"", ""6"": ""mno"", ""7"": ""pqrs"",
        ""8"": ""tuv"", ""9"": ""wxyz""
    }

    res = []

    def backtrack(i, cur):
        if i == len(digits):
            res.append(cur)
            return
        for ch in phone[digits[i]]:
            backtrack(i + 1, cur + ch)

    backtrack(0, """")
    return res
",1,GPT,"Solve the problem ""Letter Combinations of a Phone Number"".

Given a string of digits from 2 to 9,
return all possible letter combinations that the number could represent.",PYTHON

,"class Solution:
    def letterCombinations(self, digits: str) -> List[str]:
        if not digits:
            return []

        res = [""""]
        digitToChar = {
            ""2"": ""abc"",
            ""3"": ""def"",
            ""4"": ""ghi"",
            ""5"": ""jkl"",
            ""6"": ""mno"",
            ""7"": ""qprs"",
            ""8"": ""tuv"",
            ""9"": ""wxyz"",
        }

        for digit in digits:
            tmp = []
            for curStr in res:
                for c in digitToChar[digit]:
                    tmp.append(curStr + c)
            res = tmp
        return res",0,GFG,NA,PYTHON

,"from collections import Counter

def leastInterval(tasks, n):
    count = Counter(tasks)
    max_freq = max(count.values())
    max_count = sum(1 for v in count.values() if v == max_freq)

    return max(len(tasks), (max_freq - 1) * (n + 1) + max_count)
",1,GPT,"Solve the problem ""Task Scheduler"".

Given a list of tasks and a cooldown n,
return the least number of units of time needed to finish all tasks
with cooldown constraints.
",PYTHON

,"class Solution:
    def leastInterval(self, tasks: List[str], n: int) -> int:
        count = [0] * 26
        for task in tasks:
            count[ord(task) - ord('A')] += 1

        maxf = max(count)
        maxCount = 0
        for i in count:
            maxCount += 1 if i == maxf else 0

        time = (maxf - 1) * (n + 1) + maxCount
        return max(len(tasks), time)",0,GFG,NA,PYTHON

,"def combinationSum(candidates, target):
    res = []

    def backtrack(i, total, cur):
        if total == target:
            res.append(cur[:])
            return
        if i >= len(candidates) or total > target:
            return

        cur.append(candidates[i])
        backtrack(i, total + candidates[i], cur)
        cur.pop()
        backtrack(i + 1, total, cur)

    backtrack(0, 0, [])
    return res
",1,GPT,"Solve the problem ""Combination Sum"".

Given an array of distinct integers candidates and a target,
return all unique combinations where candidates sum to target.
Each number may be used unlimited times.",PYTHON

,"class Solution:
    def combinationSum(self, nums: List[int], target: int) -> List[List[int]]:
        res = []
        nums.sort()

        def dfs(i, cur, total):
            if total == target:
                res.append(cur.copy())
                return

            for j in range(i, len(nums)):
                if total + nums[j] > target:
                    return
                cur.append(nums[j])
                dfs(j, cur, total + nums[j])
                cur.pop()

        dfs(0, [], 0)
        return res",0,GFG,NA,PYTHON

,"def generateParenthesis(n):
    res = []

    def backtrack(opened, closed, cur):
        if opened == closed == n:
            res.append(cur)
            return
        if opened < n:
            backtrack(opened + 1, closed, cur + ""("")
        if closed < opened:
            backtrack(opened, closed + 1, cur + "")"")

    backtrack(0, 0, """")
    return res
",1,GPT,"Solve the problem ""Generate Parentheses"".

Given n pairs of parentheses,
generate all combinations of well-formed parentheses.

Provide Python backtracking solution.
",PYTHON

,"class Solution:
    def generateParenthesis(self, n):
        res = [[] for _ in range(n+1)]
        res[0] = [""""]

        for k in range(n + 1):
            for i in range(k):
                for left in res[i]:
                    for right in res[k-i-1]:
                        res[k].append(""("" + left + "")"" + right)

        return res[-1]",0,GFG,NA,PYTHON

,"import heapq

def lastStoneWeight(stones):
    stones = [-s for s in stones]
    heapq.heapify(stones)

    while len(stones) > 1:
        a = -heapq.heappop(stones)
        b = -heapq.heappop(stones)
        if a != b:
            heapq.heappush(stones, -(a - b))

    return -stones[0] if stones else 0
",1,GPT,"Solve the problem ""Last Stone Weight"".

Given a list of stones,
repeatedly smash the two heaviest stones.
Return the weight of the remaining stone or 0.

Provide Python solution using heap.
",PYTHON

,"class Solution:
    def lastStoneWeight(self, stones: List[int]) -> int:

        maxStone = max(stones)
        bucket = [0] * (maxStone + 1)
        for stone in stones:
            bucket[stone] += 1

        first = second = maxStone
        while first > 0:
            if bucket[first] % 2 == 0:
                first -= 1
                continue

            j = min(first - 1, second)
            while j > 0 and bucket[j] == 0:
                j -= 1

            if j == 0:
                return first
            second = j
            bucket[first] -= 1
            bucket[second] -= 1
            bucket[first - second] += 1
            first = max(first - second, second)
        return first",0,GFG,NA,PYTHON

,"import heapq

def findKthLargest(nums, k):
    return heapq.nlargest(k, nums)[-1]
",1,GPT,"Solve the problem ""Kth Largest Element in an Array"".

Given an integer array nums and an integer k,
return the kth largest element.
Do not sort the entire array.",PYTHON

,"class Solution:

    def findKthLargest(self, nums: List[int], k: int) -> int:
        k = len(nums) - k

        def quickSelect(l, r):
            pivot, p = nums[r], l
            for i in range(l, r):
                if nums[i] <= pivot:
                    nums[p], nums[i] = nums[i], nums[p]
                    p += 1
            nums[p], nums[r] = nums[r], nums[p]

            if p > k:
                return quickSelect(l, p - 1)
            elif p < k:
                return quickSelect(p + 1, r)
            else:
                return nums[p]

        return quickSelect(0, len(nums) - 1)",0,GFG,NA,PYTHON

,"def subsetsWithDup(nums):
    nums.sort()
    res = []

    def backtrack(i, cur):
        res.append(cur[:])
        for j in range(i, len(nums)):
            if j > i and nums[j] == nums[j - 1]:
                continue
            cur.append(nums[j])
            backtrack(j + 1, cur)
            cur.pop()

    backtrack(0, [])
    return res
",1,GPT,"Solve the problem ""Subsets II"".

Given an integer array nums that may contain duplicates,
return all possible subsets without duplicate subsets.",PYTHON

,"class Solution:
    def subsetsWithDup(self, nums: List[int]) -> List[List[int]]:
        nums.sort()
        res = [[]]
        prev_Idx = idx = 0

        for i in range(len(nums)):
            idx = prev_idx if i >= 1 and nums[i] == nums[i - 1] else 0
            prev_idx = len(res)
            for j in range(idx, prev_idx):
                tmp = res[j].copy()
                tmp.append(nums[i])
                res.append(tmp)

        return res",0,GFG,NA,PYTHON

,"import heapq

def minMeetingRooms(intervals):
    if not intervals:
        return 0

    intervals.sort(key=lambda x: x[0])
    heap = []

    for start, end in intervals:
        if heap and heap[0] <= start:
            heapq.heappop(heap)
        heapq.heappush(heap, end)

    return len(heap)
",1,GPT,"Solve the problem ""Meeting Rooms II"".

Given an array of meeting time intervals where intervals[i] = [start, end],
return the minimum number of conference rooms required.",PYTHON

,"""""""
Definition of Interval:
class Interval(object):
    def __init__(self, start, end):
        self.start = start
        self.end = end
""""""

class Solution:
    def minMeetingRooms(self, intervals: List[Interval]) -> int:
        time = []
        for i in intervals:
            time.append((i.start, 1))
            time.append((i.end, -1))

        time.sort(key=lambda x: (x[0], x[1]))

        res = count = 0
        for t in time:
            count += t[1]
            res = max(res, count)
        return res",0,GFG,NA,PYTHON

,"def setZeroes(matrix):
    rows, cols = len(matrix), len(matrix[0])
    row_zero = any(matrix[0][c] == 0 for c in range(cols))
    col_zero = any(matrix[r][0] == 0 for r in range(rows))

    for r in range(1, rows):
        for c in range(1, cols):
            if matrix[r][c] == 0:
                matrix[r][0] = matrix[0][c] = 0

    for r in range(1, rows):
        for c in range(1, cols):
            if matrix[r][0] == 0 or matrix[0][c] == 0:
                matrix[r][c] = 0

    if row_zero:
        for c in range(cols):
            matrix[0][c] = 0
    if col_zero:
        for r in range(rows):
            matrix[r][0] = 0
",1,GPT,"Solve the problem ""Set Matrix Zeroes"".

Given an m x n matrix,
if an element is 0, set its entire row and column to 0.
Do it in-place with constant extra space.

Provide Python solution.
",PYTHON

,"class Solution:
    def setZeroes(self, matrix: List[List[int]]) -> None:
        ROWS, COLS = len(matrix), len(matrix[0])
        rowZero = False

        for r in range(ROWS):
            for c in range(COLS):
                if matrix[r][c] == 0:
                    matrix[0][c] = 0
                    if r > 0:
                        matrix[r][0] = 0
                    else:
                        rowZero = True

        for r in range(1, ROWS):
            for c in range(1, COLS):
                if matrix[0][c] == 0 or matrix[r][0] == 0:
                    matrix[r][c] = 0

        if matrix[0][0] == 0:
            for r in range(ROWS):
                matrix[r][0] = 0

        if rowZero:
            for c in range(COLS):
                matrix[0][c] = 0",0,GFG,NA,PYTHON

,"def solveNQueens(n):
    res = []
    cols, diag1, diag2 = set(), set(), set()
    board = [["".""] * n for _ in range(n)]

    def backtrack(r):
        if r == n:
            res.append(["""".join(row) for row in board])
            return
        for c in range(n):
            if c in cols or (r - c) in diag1 or (r + c) in diag2:
                continue
            cols.add(c)
            diag1.add(r - c)
            diag2.add(r + c)
            board[r][c] = ""Q""

            backtrack(r + 1)

            cols.remove(c)
            diag1.remove(r - c)
            diag2.remove(r + c)
            board[r][c] = "".""

    backtrack(0)
    return res
",1,GPT,"Solve the problem ""N-Queens"".

Given an integer n,
return all distinct solutions to the n-queens puzzle.",PYTHON

,"class Solution:
    def solveNQueens(self, n: int) -> List[List[str]]:
        col = 0
        posDiag = 0
        negDiag = 0
        res = []
        board = [["".""] * n for i in range(n)]

        def backtrack(r):
            nonlocal col, posDiag, negDiag
            if r == n:
                copy = ["""".join(row) for row in board]
                res.append(copy)
                return
            for c in range(n):
                if ((col & (1 << c)) or (posDiag & (1 << (r + c)))
                    or (negDiag & (1 << (r - c + n)))):
                    continue
                col ^= (1 << c)
                posDiag ^= (1 << (r + c))
                negDiag ^= (1 << (r - c + n))
                board[r][c] = ""Q""

                backtrack(r + 1)

                col ^= (1 << c)
                posDiag ^= (1 << (r + c))
                negDiag ^= (1 << (r - c + n))
                board[r][c] = "".""

        backtrack(0)
        return res",0,GFG,NA,PYTHON

,"def numIslands(grid):
    if not grid:
        return 0

    rows, cols = len(grid), len(grid[0])
    count = 0

    def dfs(r, c):
        if r < 0 or c < 0 or r >= rows or c >= cols or grid[r][c] != ""1"":
            return
        grid[r][c] = ""0""
        dfs(r+1, c)
        dfs(r-1, c)
        dfs(r, c+1)
        dfs(r, c-1)

    for r in range(rows):
        for c in range(cols):
            if grid[r][c] == ""1"":
                dfs(r, c)
                count += 1

    return count
",1,GPT,"Solve the problem ""Number of Islands"".

Given a 2D grid of '1's (land) and '0's (water),
return the number of islands.",PYTHON

,"class Solution:
    def numIslands(self, grid: List[List[str]]) -> int:
        directions = [[1, 0], [-1, 0], [0, 1], [0, -1]]
        ROWS, COLS = len(grid), len(grid[0])
        islands = 0

        def bfs(r, c):
            q = deque()
            grid[r][c] = ""0""
            q.append((r, c))

            while q:
                row, col = q.popleft()
                for dr, dc in directions:
                    nr, nc = dr + row, dc + col
                    if (nr < 0 or nc < 0 or nr >= ROWS or
                        nc >= COLS or grid[nr][nc] == ""0""
                    ):
                        continue
                    q.append((nr, nc))
                    grid[nr][nc] = ""0""

        for r in range(ROWS):
            for c in range(COLS):
                if grid[r][c] == ""1"":
                    bfs(r, c)
                    islands += 1

        return islands",0,GFG,NA,PYTHON

,"from collections import deque

def orangesRotting(grid):
    rows, cols = len(grid), len(grid[0])
    q = deque()
    fresh = 0

    for r in range(rows):
        for c in range(cols):
            if grid[r][c] == 2:
                q.append((r, c))
            elif grid[r][c] == 1:
                fresh += 1

    time = 0
    directions = [(1,0), (-1,0), (0,1), (0,-1)]

    while q and fresh:
        for _ in range(len(q)):
            r, c = q.popleft()
            for dr, dc in directions:
                nr, nc = r + dr, c + dc
                if 0 <= nr < rows and 0 <= nc < cols and grid[nr][nc] == 1:
                    grid[nr][nc] = 2
                    fresh -= 1
                    q.append((nr, nc))
        time += 1

    return time if fresh == 0 else -1
",1,GPT,"Solve the problem ""Rotting Oranges"".

Given a grid where:
0 = empty, 1 = fresh, 2 = rotten,
return the minimum minutes to rot all fresh oranges.
If impossible, return -1.
",PYTHON

,"class Solution:
    def orangesRotting(self, grid: List[List[int]]) -> int:
        ROWS, COLS = len(grid), len(grid[0])
        fresh = 0
        time = 0

        for r in range(ROWS):
            for c in range(COLS):
                if grid[r][c] == 1:
                    fresh += 1

        directions = [[0, 1], [0, -1], [1, 0], [-1, 0]]

        while fresh > 0:
            flag = False
            for r in range(ROWS):
                for c in range(COLS):
                    if grid[r][c] == 2:
                        for dr, dc in directions:
                            row, col = r + dr, c + dc
                            if (row in range(ROWS) and
                                col in range(COLS) and
                                grid[row][col] == 1):
                                grid[row][col] = 3
                                fresh -= 1
                                flag = True

            if not flag:
                return -1

            for r in range(ROWS):
                for c in range(COLS):
                    if grid[r][c] == 3:
                        grid[r][c] = 2

            time += 1

        return time",0,GFG,NA,PYTHON

,"def solve(board):
    if not board:
        return

    rows, cols = len(board), len(board[0])

    def dfs(r, c):
        if r < 0 or c < 0 or r >= rows or c >= cols or board[r][c] != ""O"":
            return
        board[r][c] = ""T""
        dfs(r+1, c)
        dfs(r-1, c)
        dfs(r, c+1)
        dfs(r, c-1)

    for r in range(rows):
        dfs(r, 0)
        dfs(r, cols - 1)
    for c in range(cols):
        dfs(0, c)
        dfs(rows - 1, c)

    for r in range(rows):
        for c in range(cols):
            if board[r][c] == ""O"":
                board[r][c] = ""X""
            elif board[r][c] == ""T"":
                board[r][c] = ""O""
",1,GPT,"Solve the problem ""Surrounded Regions"".

Given a board of 'X' and 'O',
capture all regions surrounded by 'X'.",PYTHON

,"class Solution:
    def solve(self, board: List[List[str]]) -> None:
        ROWS, COLS = len(board), len(board[0])
        directions = [(1, 0), (-1, 0), (0, 1), (0, -1)]

        def capture():
            q = deque()
            for r in range(ROWS):
                for c in range(COLS):
                    if (r == 0 or r == ROWS - 1 or
                        c == 0 or c == COLS - 1 and
                        board[r][c] == ""O""
                    ):
                        q.append((r, c))
            while q:
                r, c = q.popleft()
                if board[r][c] == ""O"":
                    board[r][c] = ""T""
                    for dr, dc in directions:
                        nr, nc = r + dr, c + dc
                        if 0 <= nr < ROWS and 0 <= nc < COLS:
                            q.append((nr, nc))

        capture()
        for r in range(ROWS):
            for c in range(COLS):
                if board[r][c] == ""O"":
                    board[r][c] = ""X""
                elif board[r][c] == ""T"":
                    board[r][c] = ""O""",0,GFG,NA,PYTHON

,"from collections import deque

def ladderLength(beginWord, endWord, wordList):
    wordSet = set(wordList)
    if endWord not in wordSet:
        return 0

    q = deque([(beginWord, 1)])

    while q:
        word, steps = q.popleft()
        if word == endWord:
            return steps
        for i in range(len(word)):
            for c in ""abcdefghijklmnopqrstuvwxyz"":
                new = word[:i] + c + word[i+1:]
                if new in wordSet:
                    wordSet.remove(new)
                    q.append((new, steps + 1))

    return 0
",1,GPT,"Solve the problem ""Word Ladder"".

Given beginWord, endWord, and a wordList,
return the length of the shortest transformation sequence.",PYTHON

,"class Solution:
    def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int:
        if endWord not in wordList or beginWord == endWord:
            return 0
        m = len(wordList[0])
        wordSet = set(wordList)
        qb, qe = deque([beginWord]), deque([endWord])
        fromBegin, fromEnd = {beginWord: 1}, {endWord: 1}

        while qb and qe:
            if len(qb) > len(qe):
                qb, qe = qe, qb
                fromBegin, fromEnd = fromEnd, fromBegin
            for _ in range(len(qb)):
                word = qb.popleft()
                steps = fromBegin[word]
                for i in range(m):
                    for c in range(97, 123):
                        if chr(c) == word[i]:
                            continue
                        nei = word[:i] + chr(c) + word[i + 1:]
                        if nei not in wordSet:
                            continue
                        if nei in fromEnd:
                            return steps + fromEnd[nei]
                        if nei not in fromBegin:
                            fromBegin[nei] = steps + 1
                            qb.append(nei)
        return 0",0,GFG,NA,PYTHON

,"import heapq

def swimInWater(grid):
    n = len(grid)
    heap = [(grid[0][0], 0, 0)]
    visited = set()

    while heap:
        time, r, c = heapq.heappop(heap)
        if (r, c) in visited:
            continue
        visited.add((r, c))
        if r == n - 1 and c == n - 1:
            return time
        for dr, dc in [(1,0), (-1,0), (0,1), (0,-1)]:
            nr, nc = r + dr, c + dc
            if 0 <= nr < n and 0 <= nc < n:
                heapq.heappush(heap, (max(time, grid[nr][nc]), nr, nc))
",1,GPT,"Solve the problem ""Swim in Rising Water"".

Given an n x n grid,
return the minimum time required to swim from top-left to bottom-right.",PYTHON

,"class Solution:
    def swimInWater(self, grid: List[List[int]]) -> int:
        N = len(grid)
        visit = set()
        minH = [[grid[0][0], 0, 0]]  # (time/max-height, r, c)
        directions = [[0, 1], [0, -1], [1, 0], [-1, 0]]

        visit.add((0, 0))
        while minH:
            t, r, c = heapq.heappop(minH)
            if r == N - 1 and c == N - 1:
                return t
            for dr, dc in directions:
                neiR, neiC = r + dr, c + dc
                if (neiR < 0 or neiC < 0 or
                    neiR == N or neiC == N or
                    (neiR, neiC) in visit
                ):
                    continue
                visit.add((neiR, neiC))
                heapq.heappush(minH, [max(t, grid[neiR][neiC]), neiR, neiC])",0,GFG,NA,PYTHON

,"from collections import deque



def wallsAndGates(rooms):

    rows, cols = len(rooms), len(rooms[0])

    q = deque()



    for r in range(rows):

        for c in range(cols):

            if rooms[r][c] == 0:

                q.append((r, c))



    directions = [(1,0), (-1,0), (0,1), (0,-1)]



    while q:

        r, c = q.popleft()

        for dr, dc in directions:

            nr, nc = r + dr, c + dc

            if 0 <= nr < rows and 0 <= nc < cols and rooms[nr][nc] == 2147483647:

                rooms[nr][nc] = rooms[r][c] + 1

                q.append((nr, nc))
",1,GPT,"Solve the problem ""Walls and Gates"" (Islands and Treasure).

Given a grid with:
-1 = wall, 0 = gate, INF = empty room,
fill each empty room with distance to its nearest gate.",PYTHON

,"class Solution:
    def islandsAndTreasure(self, grid: List[List[int]]) -> None:
        ROWS, COLS = len(grid), len(grid[0])
        visit = set()
        q = deque()

        def addCell(r, c):
            if (min(r, c) < 0 or r == ROWS or c == COLS or
                (r, c) in visit or grid[r][c] == -1
            ):
                return
            visit.add((r, c))
            q.append([r, c])

        for r in range(ROWS):
            for c in range(COLS):
                if grid[r][c] == 0:
                    q.append([r, c])
                    visit.add((r, c))

        dist = 0
        while q:
            for i in range(len(q)):
                r, c = q.popleft()
                grid[r][c] = dist
                addCell(r + 1, c)
                addCell(r - 1, c)
                addCell(r, c + 1)
                addCell(r, c - 1)
            dist += 1",0,GFG,NA,PYTHON

,"def climbStairs(n):
    if n <= 2:
        return n

    a, b = 1, 2
    for _ in range(3, n + 1):
        a, b = b, a + b

    return b
",1,GPT,"Solve the problem ""Climbing Stairs"".

You can climb 1 or 2 steps at a time.
Given n steps, return how many distinct ways you can climb.",PYTHON

,"class Solution:
    def climbStairs(self, n: int) -> int:
        one, two = 1, 1

        for i in range(n - 1):
            temp = one
            one = one + two
            two = temp

        return one",0,GFG,NA,PYTHON

,"def rob(nums):
    prev, curr = 0, 0
    for n in nums:
        prev, curr = curr, max(curr, prev + n)
    return curr
",1,GPT,"Solve the problem ""House Robber"".

Given an integer array nums representing the amount of money in each house,
return the maximum amount of money you can rob without robbing adjacent houses.
",PYTHON

,"class Solution:
    def rob(self, nums: List[int]) -> int:
        rob1, rob2 = 0, 0

        for num in nums:
            temp = max(num + rob1, rob2)
            rob1 = rob2
            rob2 = temp
        return rob2",0,GFG,NA,PYTHON

,"def coinChange(coins, amount):
    dp = [amount + 1] * (amount + 1)
    dp[0] = 0

    for a in range(1, amount + 1):
        for c in coins:
            if a - c >= 0:
                dp[a] = min(dp[a], dp[a - c] + 1)

    return dp[amount] if dp[amount] != amount + 1 else -1
",1,GPT,"Solve the problem ""Coin Change"".

Given an array coins and an integer amount,
return the fewest number of coins needed to make up that amount.
If not possible, return -1.",PYTHON

,"class Solution:
    def coinChange(self, coins: List[int], amount: int) -> int:
        if amount == 0:
            return 0

        q = deque([0])
        seen = [False] * (amount + 1)
        seen[0] = True
        res = 0

        while q:
            res += 1
            for _ in range(len(q)):
                cur = q.popleft()
                for coin in coins:
                    nxt = cur + coin
                    if nxt == amount:
                        return res
                    if nxt > amount or seen[nxt]:
                        continue
                    seen[nxt] = True
                    q.append(nxt)

        return -1",0,GFG,NA,PYTHON

,"def uniquePaths(m, n):
    dp = [1] * n
    for _ in range(m - 1):
        for j in range(1, n):
            dp[j] += dp[j - 1]
    return dp[-1]
",1,GPT,"Solve the problem ""Unique Paths"".

Given m and n representing grid dimensions,
return the number of unique paths from top-left to bottom-right.",PYTHON

,"class Solution:
    def uniquePaths(self, m: int, n: int) -> int:
        dp = [1] * n
        for i in range(m - 2, -1, -1):
            for j in range(n - 2, -1, -1):
                dp[j] += dp[j + 1]

        return dp[0]",0,GFG,NA,PYTHON

,"def maxCoins(nums):
    nums = [1] + nums + [1]
    n = len(nums)
    dp = [[0] * n for _ in range(n)]

    for length in range(2, n):
        for l in range(0, n - length):
            r = l + length
            for k in range(l + 1, r):
                dp[l][r] = max(
                    dp[l][r],
                    nums[l] * nums[k] * nums[r] + dp[l][k] + dp[k][r]
                )

    return dp[0][n - 1]
",1,GPT,"Solve the problem ""Burst Balloons"".

Given an array nums,
return the maximum coins you can collect by bursting balloons wisely.",PYTHON

,"class Solution:
    def maxCoins(self, nums):
        n = len(nums)
        new_nums = [1] + nums + [1]

        dp = [[0] * (n + 2) for _ in range(n + 2)]
        for l in range(n, 0, -1):
            for r in range(l, n + 1):
                for i in range(l, r + 1):
                    coins = new_nums[l - 1] * new_nums[i] * new_nums[r + 1]
                    coins += dp[l][i - 1] + dp[i + 1][r]
                    dp[l][r] = max(dp[l][r], coins)

        return dp[1][n]",0,GFG,NA,PYTHON

,"def canJump(nums):
    max_reach = 0
    for i, n in enumerate(nums):
        if i > max_reach:
            return False
        max_reach = max(max_reach, i + n)
    return True
",1,GPT,"Solve the problem ""Jump Game"".

Given an array nums where nums[i] represents maximum jump length,
return true if you can reach the last index.",PYTHON

,"class Solution:
    def canJump(self, nums: List[int]) -> bool:
        goal = len(nums) - 1

        for i in range(len(nums) - 2, -1, -1):
            if i + nums[i] >= goal:
                goal = i
        return goal == 0",0,GFG,NA,PYTHON

,"def canCompleteCircuit(gas, cost):
    total = curr = start = 0

    for i in range(len(gas)):
        total += gas[i] - cost[i]
        curr += gas[i] - cost[i]
        if curr < 0:
            start = i + 1
            curr = 0

    return start if total >= 0 else -1
",1,GPT,"Solve the problem ""Gas Station"".

Given gas and cost arrays,
return the starting gas station index if you can travel around once.
Otherwise return -1.",PYTHON

,"class Solution:
    def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int:
        if sum(gas) < sum(cost):
            return -1

        total = 0
        res = 0
        for i in range(len(gas)):
            total += (gas[i] - cost[i])

            if total < 0:
                total = 0
                res = i + 1

        return res",0,GFG,NA,PYTHON

,"def isHappy(n):
    seen = set()

    while n != 1 and n not in seen:
        seen.add(n)
        n = sum(int(c) ** 2 for c in str(n))

    return n == 1
",1,GPT,"Solve the problem ""Happy Number"".

Determine if a number is happy.
Use cycle detection or a set.

Provide Python solution.
",PYTHON

,"class Solution:
    def isHappy(self, n: int) -> bool:
        slow, fast = n, self.sumOfSquares(n)
        power = lam = 1

        while slow != fast:
            if power == lam:
                slow = fast
                power *= 2
                lam = 0
            fast = self.sumOfSquares(fast)
            lam += 1
        return True if fast == 1 else False

    def sumOfSquares(self, n: int) -> int:
        output = 0

        while n:
            digit = n % 10
            digit = digit ** 2
            output += digit
            n = n // 10
        return output",0,GFG,NA,PYTHON

,"def isInterleave(s1, s2, s3):
    if len(s1) + len(s2) != len(s3):
        return False

    dp = [[False] * (len(s2) + 1) for _ in range(len(s1) + 1)]
    dp[0][0] = True

    for i in range(len(s1) + 1):
        for j in range(len(s2) + 1):
            if i > 0:
                dp[i][j] |= dp[i - 1][j] and s1[i - 1] == s3[i + j - 1]
            if j > 0:
                dp[i][j] |= dp[i][j - 1] and s2[j - 1] == s3[i + j - 1]

    return dp[-1][-1]
",1,GPT,"Solve the problem ""Interleaving String"".

Given strings s1, s2, and s3,
determine if s3 is formed by interleaving s1 and s2.",PYTHON

,"class Solution:
    def isInterleave(self, s1: str, s2: str, s3: str) -> bool:
        m, n = len(s1), len(s2)
        if m + n != len(s3):
            return False
        if n < m:
            s1, s2 = s2, s1
            m, n = n, m

        dp = [False for _ in range(n + 1)]
        dp[n] = True
        for i in range(m, -1, -1):
            nextDp = True if i == m else False
            for j in range(n, -1, -1):
                res = False if j < n else nextDp
                if i < m and s1[i] == s3[i + j] and dp[j]:
                    res = True
                if j < n and s2[j] == s3[i + j] and nextDp:
                    res = True
                dp[j] = res
                nextDp = dp[j]
        return dp[0]",0,GFG,NA,PYTHON

,"def findTargetSumWays(nums, target):
    total = sum(nums)
    if abs(target) > total or (total + target) % 2:
        return 0

    s = (total + target) // 2
    dp = [0] * (s + 1)
    dp[0] = 1

    for num in nums:
        for i in range(s, num - 1, -1):
            dp[i] += dp[i - num]

    return dp[s]
",1,GPT,"Solve the problem ""Target Sum"".

Given an array nums and a target,
return the number of ways to assign + or - to reach target.",PYTHON

,"class Solution:
    def findTargetSumWays(self, nums: List[int], target: int) -> int:
        dp = defaultdict(int)
        dp[0] = 1

        for num in nums:
            next_dp = defaultdict(int)
            for total, count in dp.items():
                next_dp[total + num] += count
                next_dp[total - num] += count
            dp = next_dp

        return dp[target]",0,GFG,NA,PYTHON

,"def numDecodings(s):
    if not s or s[0] == ""0"":
        return 0

    dp1, dp2 = 1, 1

    for i in range(1, len(s)):
        cur = 0
        if s[i] != ""0"":
            cur += dp2
        if 10 <= int(s[i - 1:i + 1]) <= 26:
            cur += dp1
        dp1, dp2 = dp2, cur

    return dp2
",1,GPT,"Solve the problem ""Decode Ways"".

Given a string s containing digits,
return the number of ways to decode it.",PYTHON

,"class Solution:
    def numDecodings(self, s: str) -> int:
        dp = dp2 = 0
        dp1 = 1
        for i in range(len(s) - 1, -1, -1):
            if s[i] == ""0"":
                dp = 0
            else:
                dp = dp1

            if i + 1 < len(s) and (s[i] == ""1"" or
               s[i] == ""2"" and s[i + 1] in ""0123456""
            ):
                dp += dp2
            dp, dp1, dp2 = 0, dp, dp1
        return dp1",0,GFG,NA,PYTHON

,"import json

json_obj =  '{ ""Name"":""David"", ""Class"":""I"", ""Age"":6 }'

python_obj = json.loads(json_obj)

print(""\nJSON data:"")

print(python_obj)

print(""\nName: "",python_obj[""Name""])

print(""Class: "",python_obj[""Class""])

print(""Age: "",python_obj[""Age""]) 
",0,WE3RESOURCE,NA,PYTHON

,"import requests

from requests.exceptions import SSLError, RequestException



url = ""https://www.google.com""  # valid SSL certificate



try:

    # By default, verify=True, so SSL certificates are checked

    response = requests.get(url, timeout=10)

    print(""Status Code:"", response.status_code)

    print(""SSL certificate verified successfully."")



except SSLError as ssl_err:

    print(""SSL Certificate verification failed!"")

    print(ssl_err)



except RequestException as req_err:

    print(""Request failed:"")

    print(req_err)
",1,GPT," Write a Python program to verifiy SSL certificates for HTTPS requests using requests module.

Note: Requests verifies SSL certificates for HTTPS requests, just like a web browser. By default, SSL verification is enabled, and Requests will throw a SSLError if it's unable to verify the certificate",PYTHON
,"import json
# a Python object (dict):
python_obj = {
  ""name"": ""David"",
  ""class"":""I"",
  ""age"": 6  
}
print(type(python_obj))
# convert into JSON:
j_data = json.dumps(python_obj)

# result is a JSON string:
print(j_data)
",0,WE3RESOURCE,NA,PYTHON
,"import requests

url = ""https://www.example.com""

# Send GET request
response = requests.get(url)

print(""URL:"", response.url)
print(""Status Code:"", response.status_code)
print(""Reason:"", response.reason)
print(""Encoding:"", response.encoding)

print(""\nHeaders:"")
for key, value in response.headers.items():
    print(f""{key}: {value}"")

print(""\nHistory (Redirects):"")
print(response.history)

print(""\nCookies:"")
print(response.cookies)

print(""\nElapsed Time:"")
print(response.elapsed)

print(""\nRequest Info:"")
print(""Method:"", response.request.method)
print(""Request URL:"", response.request.url)
print(""Request Headers:"", response.request.headers)

print(""\nContent (first 500 bytes):"")
print(response.content[:500])
",1,GPT," Write a Python program to display the contains of different attributes like different attributes like status_code, headers, url, history, encoding, reason, cookies, elapsed, request and content of a specified resource.",PYTHON
,"import json
python_dict =  {""name"": ""David"", ""age"": 6, ""class"":""I""}
python_list =  [""Red"", ""Green"", ""Black""]
python_str =  ""Python Json""
python_int =  (1234)
python_float =  (21.34)
python_T =  (True)
python_F =  (False)
python_N =  (None)

json_dict = json.dumps(python_dict)
json_list = json.dumps(python_list)
json_str = json.dumps(python_str)
json_num1 = json.dumps(python_int)
json_num2 = json.dumps(python_float)
json_t = json.dumps(python_T)
json_f = json.dumps(python_F)
json_n = json.dumps(python_N)

print(""json dict : "", json_dict)
print(""jason list : "", json_list)
print(""json string : "", json_str)
print(""json number1 : "", json_num1)
print(""json number2 : "", json_num2)
print(""json true : "", json_t)
print(""json false : "", json_f)
print(""json null ; "", json_n)
",0,WE3RESOURCE,NA,PYTHON
,"import requests
import datetime

def get_m4_5_plus_count(start_time: str, end_time: str) -> int:
    """"""
    Returns the number of earthquakes globally with magnitude >= 4.5
    between start_time and end_time (ISO format).
    """"""
    url = ""https://earthquake.usgs.gov/fdsnws/event/1/query""
    params = {
        ""format"": ""geojson"",
        ""starttime"": start_time,
        ""endtime"": end_time,
        ""minmagnitude"": 4.5,
    }

    response = requests.get(url, params=params)

    if response.status_code == 200:
        data = response.json()
        # 'count' field in 'metadata' holds the number of matching events
        return data.get(""metadata"", {}).get(""count"", 0)
    else:
        print(f""Error: {response.status_code}"")
        return 0

if __name__ == ""__main__"":
    # Set time period (last 30 days)
    end_time = datetime.datetime.utcnow().date().isoformat()
    start_time = (datetime.datetime.utcnow() - datetime.timedelta(days=30)).date().isoformat()
    
    count = get_m4_5_plus_count(start_time, end_time)
    print(f""Number of earthquakes with magnitude >= 4.5 between {start_time} and {end_time}: {count}"")
",1,GPT,Write a Python program to get the number of magnitude 4.5+ earthquakes detected worldwide by the USGS.,PYTHON
,"import json
j_str = {'4': 5, '6': 7, '1': 3, '2': 4}
print(""Original String:"")
print(j_str)
print(""\nJSON data:"")
print(json.dumps(j_str, sort_keys=True, indent=4))
",0,WE3RESOURCE,NA,PYTHON
,"import requests
import random

API_KEY = ""YOUR_TMDB_API_KEY""   # <-- replace with your API key
BASE_URL = ""https://api.themoviedb.org/3""

# Step 1: Get popular movies (several pages available)
popular_url = f""{BASE_URL}/movie/popular""
params = {
    ""api_key"": API_KEY,
    ""language"": ""en-US"",
    ""page"": random.randint(1, 20)  # random page for randomness
}

response = requests.get(popular_url, params=params)
response.raise_for_status()

movies = response.json()[""results""]

# Step 2: Randomly select 10 movies
random_movies = random.sample(movies, 10)

print(""Top 10 Random Movies:\n"")

for i, movie in enumerate(random_movies, start=1):
    title = movie[""title""]
    year = movie[""release_date""][:4] if movie[""release_date""] else ""N/A""
    summary = movie[""overview""]

    print(f""{i}. Movie Name : {title}"")
    print(f""   Year       : {year}"")
    print(f""   Summary    : {summary}\n"")
",1,GPT,"Write a Python program to get movie name, year and a brief summary of the top 10 random movies",PYTHON
,"import json

jobj_dict =  '{""name"": ""David"", ""age"": 6, ""class"": ""I""}'
jobj_list =   '[""Red"", ""Green"", ""Black""]'
jobj_string = '""Python Json""'
jobj_int = '1234'
jobj_float =  '21.34'
python_dict =  json.loads(jobj_dict)
python_list = json.loads(jobj_list)
python_str =  json.loads(jobj_string)
python_int =   json.loads(jobj_int)
python_float = json.loads(jobj_float)

print(""Python dictionary: "", python_dict)
print(""Python list: "", python_list)
print(""Python string: "", python_str)
print(""Python integer: "", python_int)
print(""Python float: "", python_float)
",0,WE3RESOURCE,NA,PYTHON
,"import requests, time
from bs4 import BeautifulSoup

B=""https://www.imdb.com""; H={""User-Agent"":""Mozilla/5.0""}
s=BeautifulSoup(requests.get(B+""/chart/top/"",headers=H).text,""html.parser"")

for m in s.select(""td.titleColumn""):
    t=m.a.text; y=m.span.text.strip(""()""); u=B+m.a[""href""]
    d=BeautifulSoup(requests.get(u,headers=H).text,""html.parser"").select(""div.credit_summary_item"")
    dr="", "".join(a.text for a in d[0].select(""a""))
    st="", "".join(a.text for a in d[1].select(""a"") if ""name"" in a[""href""])
    print(f""{t} ({y}) | Dir: {dr} | Stars: {st}"")
    time.sleep(0.5)
",1,GPT,"Write a Python program to download IMDB's Top 250 data (movie name, Initial release, director name and stars).GIVE ME THE CODE AS SHORT AS POSSIBLE",PYTHON

,"import json



with open('states.json') as f:

  state_data= json.load(f)



for state in state_data['states']:

  del state['area_codes']



with open('new_states.json', 'w') as f:

  json.dump(state_data, f, indent=2)
",0,WE3RESOURCE,NA,PYTHON

,"import requests

from bs4 import BeautifulSoup



url = ""https://mlh.io/seasons/2026/events""

headers = {""User-Agent"":""Mozilla/5.0""}



# Fetch event list

resp = requests.get(url, headers=headers)

soup = BeautifulSoup(resp.text, ""html.parser"")



events = soup.select("".event-card"")[:25]  # next 25 events



print(f""{'Date':<20}{'Days':<10}{'Title':<50}{'City':<20}{'Country'}"")



for e in events:

    date = e.select_one("".event-date"").text.strip() if e.select_one("".event-date"") else ""N/A""

    title = e.select_one("".event-name"").text.strip() if e.select_one("".event-name"") else ""N/A""

    location = e.select_one("".event-location"").text.strip().split("","") if e.select_one("".event-location"") else [""N/A""]

    city = location[0].strip() if len(location)>0 else ""N/A""

    country = location[-1].strip() if len(location)>1 else ""N/A""



    # compute approximate event duration if date range present

    days = ""1"" if ""-"" not in date else date.split(""-"")[1].strip()



    print(f""{date:<20}{days:<10}{title:<50}{city:<20}{country}"")
",1,GPT,"Write a Python program to display the date, days, title, city, country of next 25 Hackevents.",PYTHON

,"import json



def encode_complex(object):

    # check using isinstance method

    if isinstance(object, complex):

        return [object.real, object.imag]

    # raised error if object is not complex

    raise TypeError(repr(object) + "" is not JSON serialized"")



complex_obj = json.dumps(2 + 3j, default=encode_complex)

print(complex_obj) 
",0,WE3RESOURCE,NA,PYTHON

,"import requests



API_KEY = ""YOUR_API_KEY_HERE""   # <-- put your API key here



city = input(""Enter city name: "")



url = ""https://api.openweathermap.org/data/2.5/weather""

params = {

    ""q"": city,

    ""appid"": API_KEY,

    ""units"": ""metric""   # Celsius

}



try:

    r = requests.get(url, params=params, timeout=10)

    r.raise_for_status()

    data = r.json()



    temp = data[""main""][""temp""]

    wind = data[""wind""][""speed""]

    weather = data[""weather""][0][""main""]

    desc = data[""weather""][0][""description""]



    print(""\nLive Weather Report"")

    print(""-------------------"")

    print(""City        :"", city)

    print(""Temperature :"", temp, ""°C"")

    print(""Wind Speed  :"", wind, ""m/s"")

    print(""Weather     :"", weather)

    print(""Description :"", desc)



except requests.exceptions.RequestException as e:

    print(""Error fetching weather data:"", e)
",1,GPT," Write a Python program to find the live weather report (temperature, wind speed, description and weather) of a given city.let the code u give me be efficient and clear ",PYTHON

,"import json

def is_complex_num(objct):

    if '__complex__' in objct:

        return complex(objct['real'], objct['img'])

    return objct



complex_object =json.loads('{""__complex__"": true, ""real"": 4, ""img"": 5}', object_hook = is_complex_num)

simple_object =json.loads('{""real"": 4, ""img"": 3}', object_hook = is_complex_num)

print(""Complex_object: "",complex_object)

print(""Without complex object: "",simple_object)

",0,WE3RESOURCE,NA,PYTHON

,"import snscrape.modules.twitter as sntwitter

username = input(""Enter Twitter username: "")

count = 0
for i, _ in enumerate(sntwitter.TwitterUserScraper(username).get_items()):
    if i == 1000: break
    count += 1

print(f""Tweets counted (latest 1000 max): {count}"")
",1,GPT,Write a Python program to scrap number of tweets of a given Twitter account. ASK THE USER TO INPUT THIER ACCOUNT ,PYTHON

,"import json
python_obj = '{""a"":  1, ""a"":  2, ""a"":  3, ""a"": 4, ""b"": 1, ""b"": 2}'
print(""Original Python object:"")
print(python_obj)
json_obj = json.loads(python_obj)
print(""\nUnique Key in a JSON object:"")
print(json_obj) 
",0,WE3RESOURCE,NA,PYTHON

,"import tweepy

# Replace with your actual bearer token from Twitter Developer Portal
BEARER_TOKEN = 'YOUR_BEARER_TOKEN_HERE'

# Initialize the client with bearer token (sufficient for read access)
client = tweepy.Client(bearer_token=BEARER_TOKEN)

# Input for Twitter username (without @)
username = input(""Enter Twitter username: "")

try:
    # Get the user by username
    user = client.get_user(username=username)
    
    if user.data:
        # Access public_metrics which includes total tweet count
        public_metrics = user.data.public_metrics
        tweet_count = public_metrics['tweet_count']
        
        print(f""@{username} has posted {tweet_count:,} tweets (including retweets and replies)."")
    else:
        print(""User not found."")
        
except tweepy.TweepyException as e:
    print(f""Error: {e}"")
",1,PERPLEXITY,Write a Python program to count number of tweets by a given Twitter account. add a input feature where the user would give their account as an input .,PYTHON

,"from urllib.request import urlopen

from bs4 import BeautifulSoup

html = urlopen('https://www.wikipedia.org/')

bs = BeautifulSoup(html, ""html.parser"")

nameList = bs.findAll('a', {'class' : 'link-box'})

for name in nameList:

  print(name.get_text())

  ",0,WE3RESOURCE,NA,PYTHON

,"import tweepy



# Replace with your actual bearer token from X Developer Portal

BEARER_TOKEN = 'YOUR_BEARER_TOKEN_HERE'



# Initialize the client with bearer token (sufficient for read access)

client = tweepy.Client(bearer_token=BEARER_TOKEN)



# Input for Twitter username (without @)

username = input(""Enter Twitter username: "")



try:

    # Get the user by username

    user = client.get_user(username=username, user_fields=['public_metrics'])

    

    if user.data:

        # Access public_metrics.like_count for number of liked posts

        public_metrics = user.data.public_metrics

        likes_count = public_metrics['like_count']

        

        print(f""@{username} has liked {likes_count:,} posts."")

    else:

        print(""User not found."")

        

except tweepy.TweepyException as e:

    print(f""Error: {e}"")
",1,PERPLEXITY,Write a Python program to get the number of post on Twitter liked by a given account,PYTHON

,"#https://bit.ly/2lVhlLX

# via: https://analytics.usa.gov/

import requests

url = 'https://analytics.usa.gov/data/live/realtime.json'

j = requests.get(url).json()

print(""Number of people visiting a U.S. government website-"")

print(""Active Users Right Now:"")

print(j['data'][0]['active_visitors'])

  ",0,WE3RESOURCE,NA,PYTHON

,"import tweepy



# Replace with your actual bearer token from X Developer Portal

BEARER_TOKEN = 'YOUR_BEARER_TOKEN_HERE'



# Initialize the client with bearer token (sufficient for read access)

client = tweepy.Client(bearer_token=BEARER_TOKEN)



# Input for Twitter username (without @)

username = input(""Enter Twitter username: "")



try:

    # Get the user by username with public_metrics

    user = client.get_user(username=username, user_fields=['public_metrics'])

    

    if user.data:

        # Access public_metrics.following count

        public_metrics = user.data.public_metrics

        following_count = public_metrics['following']

        

        print(f""@{username} is following {following_count:,} accounts."")

    else:

        print(""User not found."")

        

except tweepy.TweepyException as e:

    print(f""Error: {e}"")
",1,PERPLEXITY,Write a Python program to get the number of following on a Twitter account.,PYTHON

,"#https://bit.ly/2lVhlLX

import requests

from lxml import html

url = 'https://www.us-cert.gov/ncas/alerts'

doc = html.fromstring(requests.get(url).text)

print(""The number of security alerts issued by US-CERT in the current year:"")

print(len(doc.cssselect('.item-list li')))

  ",0,WE3RESOURCE,NA,PYTHON

,"import tweepy



client = tweepy.Client(bearer_token='YOUR_BEARER_TOKEN_HERE')

username = input(""Enter Twitter username: "")



try:

    user = client.get_user(username=username, user_fields=['public_metrics'])

    print(f""@{username} has {user.data.public_metrics['followers_count']:,} followers"")

except:

    print(""Error fetching data"")
",1,PERPLEXITY,Write a Python program to get the number of followers of a given twitter account. GIVE THE CODE IN FEWER LINES FOR EFFECTIVENESS,PYTHON

,"#https://bit.ly/2lVhlLX

import requests

from lxml import html

url = 'http://www.state.gov/r/pa/ode/socialmedia/'

doc = html.fromstring(requests.get(url).text)

pinlinks = [a for a in doc.cssselect('a') if 'pinterest.com' in str(a.attrib.get('href'))]

print(""The number of Pinterest accounts maintained by U.S. State Department embassies and missions:"")

print(len(pinlinks))

  ",0,WE3RESOURCE,NA,PYTHON

,"import requests

from lxml import html



url = 'https://www.state.gov/r/pa/ode/socialmedia/'

doc = html.fromstring(requests.get(url).text)

pinterest_links = [a for a in doc.cssselect('a') if 'pinterest.com' in str(a.attrib.get('href'))]

print(f""Number of Pinterest accounts: {len(pinterest_links)}"")
",1,PERPLEXITY," Write a Python program to get the number of Pinterest accounts maintained by U.S. State Department embassies and missions.

Source: https://www.state.gov/r/pa/ode/socialmedia/",PYTHON

,"from bs4 import BeautifulSoup

import requests

handle = input('Input your account name on Twitter: ') 

temp = requests.get('https://twitter.com/'+handle)

bs = BeautifulSoup(temp.text,'lxml')

try:

    follow_box = bs.find('li',{'class':'ProfileNav-item ProfileNav-item--followers'})

    followers = follow_box.find('a').find('span',{'class':'ProfileNav-value'})

    print(""Number of followers: {} "".format(followers.get('data-count')))

except:

    print('Account name not found...')

  ",0,WERESOURCE,NA,PYTHON

,"import requests

from bs4 import BeautifulSoup

from datetime import datetime



url = 'https://www.us-cert.gov/ncas/alerts'

response = requests.get(url)

soup = BeautifulSoup(response.text, 'html.parser')



# Current year

current_year = datetime.now().year

alerts = soup.find_all('article', {'data-year': str(current_year)})



print(f""US-CERT security alerts in {current_year}: {len(alerts)}"")
",1,PERPLEXITY,"Write a Python program get the number of security alerts issued by US-CERT in the current year.

Source: https://www.us-cert.gov/ncas/alerts",PYTHON

,"from bs4 import BeautifulSoup

import requests



handle = input('Input your account name on Twitter: ') 

temp = requests.get('https://twitter.com/'+handle)

bs = BeautifulSoup(temp.text,'lxml')



try:

    favorite_box = bs.find('li',{'class':'ProfileNav-item ProfileNav-item--favorites'})

    favorite = favorite_box.find('a').find('span',{'class':'ProfileNav-value'})

    print(""Number of post {}  liked are {}: "".format(handle,favorite.get('data-count')))



except:

    print('Account name not found...')

  ",0,WERESOURCE,NA,PYTHON

,"import requests

import json



url = 'https://analytics.usa.gov/data/live/realtime.json'

data = requests.get(url).json()

active_users = data['totals']['activeUsers']

print(f""Currently {active_users:,} people visiting U.S. government websites"")
",1,PERPLEXITY,"Write a Python program to get the number of people visiting a U.S. government website right now.

Source: https://analytics.usa.gov/data/live/realtime.json",PYTHON

,"from bs4 import BeautifulSoup

import requests



handle = input('Input your account name on Twitter: ') 

temp = requests.get('https://twitter.com/'+handle)

bs = BeautifulSoup(temp.text,'lxml')



try:

    following_box = bs.find('li',{'class':'ProfileNav-item ProfileNav-item--following'})

    following = following_box.find('a').find('span',{'class':'ProfileNav-value'})

    print(""{} is following {} people."".format(handle,following.get('data-count')))



except:

    print('Account name not found...')

  ",0,WERESOURCE,NA,PYTHON

,"import requests

from bs4 import BeautifulSoup



url = 'https://www.wikipedia.org/'

soup = BeautifulSoup(requests.get(url).text, 'html.parser')



langs = soup.find('ul', class_='languages').find_all('li')

for lang in langs:

    name = lang.text.strip()

    count = lang.a['title'].split(' ')[0].replace(',', '')

    print(f""{name}: {count}"")
",1,PERPLEXITY,Write a Python program to list all language names and number of related articles in the order they appear in wikipedia.org.,PYTHON

,"from bs4 import BeautifulSoup

import requests



handle = input('Input your account name on Twitter: ')

temp = requests.get('https://twitter.com/'+handle)

bs = BeautifulSoup(temp.text,'lxml')



try:

    tweet_box = bs.find('li',{'class':'ProfileNav-item ProfileNav-item--tweets is-active'})

    tweets= tweet_box.find('a').find('span',{'class':'ProfileNav-value'})

    print(""{} tweets {} number of tweets."".format(handle,tweets.get('data-count')))



except:

    print('Account name not found...')

  ",0,WERESOURCE,NA,PYTHON

,"import json

import io



def convert_json_to_object(data_source):

    """"""

    Converts JSON data from various forms (string, file, or stream) 

    into a Python object.

    """"""

    try:

        # Case 1: If data_source is already a file-like object/stream

        if hasattr(data_source, 'read'):

            return json.load(data_source)

        

        # Case 2: If data_source is a string

        if isinstance(data_source, str):

            # Check if it's a file path by looking for a .json extension
            if data_source.strip().endswith('.json'):
                with open(data_source, 'r', encoding='utf-8') as f:
                    return json.load(f)
            # Otherwise, treat it as a raw JSON string
            return json.loads(data_source)
        
        # Case 3: If data_source is bytes
        if isinstance(data_source, bytes):
            return json.loads(data_source.decode('utf-8'))
            
        raise ValueError(""Unsupported data format."")

    except json.JSONDecodeError as e:
        return f""Invalid JSON: {e}""
    except FileNotFoundError:
        return ""Error: The specified file was not found.""

# --- Examples of Usage ---

# 1. From a JSON String
json_string = '{""name"": ""Alice"", ""role"": ""Engineer"", ""active"": true}'
obj_from_str = convert_json_to_object(json_string)

# 2. From a File-like object (Stream)
stream = io.StringIO('[1, 2, 3, {""key"": ""value""}]')
obj_from_stream = convert_json_to_object(stream)

print(f""String conversion: {obj_from_str['name']}"")
print(f""Stream conversion: {obj_from_stream[3]['key']}"")",1,GEMINI,Write a Python program to convert JSON data to Python object.Make the code effiecient to accept the json in various countforms,PYTHON
,"from bs4 import BeautifulSoup
import requests
handle = input('Input your account name on Twitter: ')
ctr = int(input('Input number of tweets to scrape: '))
res=requests.get('https://twitter.com/'+ handle)
bs=BeautifulSoup(res.content,'lxml')
all_tweets = bs.find_all('div',{'class':'tweet'})
if all_tweets:
  for tweet in all_tweets[:ctr]:
    context = tweet.find('div',{'class':'context'}).text.replace(""\n"","" "").strip()
    content = tweet.find('div',{'class':'content'})
    header = content.find('div',{'class':'stream-item-header'})
    user = header.find('a',{'class':'account-group js-account-group js-action-profile js-user-profile-link js-nav'}).text.replace(""\n"","" "").strip()
    time = header.find('a',{'class':'tweet-timestamp js-permalink js-nav js-tooltip'}).find('span').text.replace(""\n"","" "").strip()
    message = content.find('div',{'class':'js-tweet-text-container'}).text.replace(""\n"","" "").strip()
    footer = content.find('div',{'class':'stream-item-footer'})
    stat = footer.find('div',{'class':'ProfileTweet-actionCountList u-hiddenVisually'}).text.replace(""\n"","" "").strip()
    if context:
      print(context)
    print(user,time)
    print(message)
    print(stat)
    print()
else:
    print(""List is empty/account name not found."")
  ",0,WERESOURCE,NA,PYTHON
,"import json

def convert_to_json(data, indent=4):
    """"""
    Converts a Python object to a JSON string.
    Includes a fallback for custom objects that aren't natively serializable.

    """"""

    try:

        # indent=4 makes the output 'pretty' and readable

        # sort_keys=True organizes the dictionary keys alphabetically

        return json.dumps(data, indent=indent, sort_keys=True, default=str)

    except Exception as e:

        return f""Error converting to JSON: {e}""



# --- Examples of Usage ---



# 1. Converting a standard Dictionary

user_profile = {

    ""username"": ""coder_123"",

    ""id"": 882,

    ""tags"": [""python"", ""api"", ""json""],

    ""is_premium"": False,

    ""location"": None

}



json_output = convert_to_json(user_profile)

print(""--- Standard Dictionary to JSON ---"")

print(json_output)



# 2. Converting to a JSON File

with open(""data.json"", ""w"", encoding=""utf-8"") as f:

    json.dump(user_profile, f, indent=4)

    print(""\n[System] Data successfully written to data.json"")",1,GEMINI,Write a Python program to convert Python object to JSON data.,PYTHON

,"import requests

from pprint import pprint

def weather_data(query):

	res=requests.get('http://api.openweathermap.org/data/2.5/weather?'+query+'&APPID=****************************8&units=metric');

	return res.json();

def print_weather(result,city):

	print(""{}'s temperature: {}°C "".format(city,result['main']['temp']))
	print(""Wind speed: {} m/s"".format(result['wind']['speed']))
	print(""Description: {}"".format(result['weather'][0]['description']))
	print(""Weather: {}"".format(result['weather'][0]['main']))
def main():
	city=input('Enter the city:')
	print()
	try:
	  query='q='+city;
	  w_data=weather_data(query);
	  print_weather(w_data, city)
	  print()
	except:
	  print('City name not found...')
if __name__=='__main__':
	main()
  ",0,WERESOURCE,NA,PYTHON
,"import json

def python_to_json_display(data):
    # Convert Python object to a JSON formatted string
    # indent=4 adds whitespace for readability
    # sort_keys=True keeps the output consistent
    json_string = json.dumps(data, indent=4, sort_keys=True)
    
    print(""--- Generated JSON String ---"")
    print(json_string)
    
    # To ""print all values"" specifically from the resulting JSON
    # we first load it back to iterate through it
    print(""\n--- Individual Values Extracted ---"")
    parsed_data = json.loads(json_string)
    
    if isinstance(parsed_data, dict):
        for key, value in parsed_data.items():
            print(f""Key: {key:12} | Value: {value} ({type(value).__name__})"")

# Example Python Object (Dictionary)
employee_data = {
    ""name"": ""Marcus Aurelius"",
    ""department"": ""Philosophy"",
    ""years_active"": 19,
    ""is_remote"": True,
    ""skills"": [""Leadership"", ""Writing"", ""Logic""],
    ""office_id"": None
}

if __name__ == ""__main__"":
    python_to_json_display(employee_data)",1,GEMINI,Write a Python program to convert Python objects into JSON strings. Print all the values.,PYTHON
,"import requests
from bs4  import BeautifulSoup
res = requests.get('https://hackevents.co/hackathons')
bs = BeautifulSoup(res.text, 'lxml')
hacks_data = bs.find_all('div',{'class':'hackathon '})
for i,f in enumerate(hacks_data,1):
    hacks_month = f.find('div',{'class':'date'}).find('div',{'class':'date-month'}).text.strip()
    hacks_date = f.find('div',{'class':'date'}).find('div',{'class':'date-day-number'}).text.strip()
    hacks_days = f.find('div',{'class':'date'}).find('div',{'class':'date-week-days'}).text.strip()
    hacks_final_date = ""{} {}, {} "".format(hacks_date, hacks_month, hacks_days )
    hacks_name = f.find('div',{'class':'info'}).find('h2').text.strip()
    hacks_city = f.find('div',{'class':'info'}).find('p').find('span',{'class':'city'}).text.strip()
    hacks_country = f.find('div',{'class':'info'}).find('p').find('span',{'class':'country'}).text.strip()
    print(""{:<5}{:<15}: {:<90}: {}, {}\n "".format(str(i)+')',hacks_final_date, hacks_name.title(), hacks_city, hacks_country))
  ",0,WERESOURCE,NA,PYTHON
,"import json

def convert_dict_to_sorted_json(data_dict):
    """"""
    Converts a dictionary to a JSON string sorted by keys 
    with an indent of 4 spaces.
    """"""
    try:
        # sort_keys=True: Alphabetizes the keys
        # indent=4: Adds 4 spaces for nested members
        json_output = json.dumps(data_dict, sort_keys=True, indent=4)
        
        print(""Successfully converted to Sorted JSON:"")
        print(json_output)
        
        return json_output
    except (TypeError, ValueError) as e:
        print(f""Error converting object: {e}"")
        return None

# Example dictionary with unsorted keys
blog_post = {
    ""title"": ""Python JSON Guide"",
    ""author"": ""Jane Doe"",
    ""views"": 1500,
    ""tags"": [""python"", ""json"", ""tutorial""],
    ""published"": True,
    ""category"": ""Programming""
}

# Execute conversion
convert_dict_to_sorted_json(blog_post)",1,GEMINI,Write a Python program to convert Python dictionary object (sort by key) to JSON data. Print the object members with indent level 4.,PYTHON
,"#https://bit.ly/2NyxdAG
from bs4 import BeautifulSoup
import requests
import re

# Download IMDB's Top 250 data

url = 'http://www.imdb.com/chart/top'

response = requests.get(url)

soup = BeautifulSoup(response.text, 'lxml')



movies = soup.select('td.titleColumn')

links = [a.attrs.get('href') for a in soup.select('td.titleColumn a')]

crew = [a.attrs.get('title') for a in soup.select('td.titleColumn a')]

ratings = [b.attrs.get('data-value') for b in soup.select('td.posterColumn span[name=ir]')]

votes = [b.attrs.get('data-value') for b in soup.select('td.ratingColumn strong')]



imdb = []



# Store each item into dictionary (data), then put those into a list (imdb)

for index in range(0, len(movies)):

    # Seperate movie into: 'place', 'title', 'year'

    movie_string = movies[index].get_text()

    movie = (' '.join(movie_string.split()).replace('.', ''))

    movie_title = movie[len(str(index))+1:-7]

    year = re.search('\((.*?)\)', movie_string).group(1)

    place = movie[:len(str(index))-(len(movie))]

    data = {""movie_title"": movie_title,

            ""year"": year,

            ""place"": place,

            ""star_cast"": crew[index],

            ""rating"": ratings[index],

            ""vote"": votes[index],

            ""link"": links[index]}

    imdb.append(data)



for item in imdb:

    print(item['place'], '-', item['movie_title'], '('+item['year']+') -', 'Starring:', item['star_cast'])

  ",0,WERESOURCE,NA,PYTHON

,"import json



# JSON encoded data (often received from an API or web request)

json_data = '''
{
    ""company"": ""TechFlow"",
    ""location"": ""San Francisco"",
    ""employees"": 150,
    ""is_hiring"": true,
    ""tech_stack"": [""Python"", ""React"", ""PostgreSQL""],
    ""revenue"": null
}
'''



def decode_json(json_string):

    try:

        # Convert JSON string to Python object (Dictionary)

        python_obj = json.loads(json_string)

        

        print(""Successfully converted JSON to Python Object:"")

        print(f""Type: {type(python_obj)}"")

        print(""-"" * 30)

        

        # Accessing the data using Python keys

        print(f""Company Name: {python_obj['company']}"")

        print(f""Main Language: {python_obj['tech_stack'][0]}"")

        print(f""Hiring Status: {python_obj['is_hiring']}"")

        

        return python_obj

        

    except json.JSONDecodeError as e:

        print(f""Failed to decode JSON: {e}"")



# Execute the conversion

decoded_data = decode_json(json_data)",1,GEMINI,Write a Python program to convert JSON encoded data into Python objects.,PYTHON

,"from bs4 import BeautifulSoup

import requests

import random

def get_imd_movies(url):

    page = requests.get(url)

    soup = BeautifulSoup(page.text, 'html.parser')

    movies = soup.find_all(""td"", class_=""titleColumn"")

    random.shuffle(movies)

    return movies

def get_imd_summary(url):

    movie_page = requests.get(url)

    soup = BeautifulSoup(movie_page.text, 'html.parser')

    return soup.find(""div"", class_=""summary_text"").contents[0].strip()



def get_imd_movie_info(movie):

    movie_title = movie.a.contents[0]

    movie_year = movie.span.contents[0]

    movie_url = 'http://www.imdb.com' + movie.a['href']

    return movie_title, movie_year, movie_url



def imd_movie_picker():

    ctr=0

    print(""--------------------------------------------"")

    for movie in get_imd_movies('http://www.imdb.com/chart/top'):

        movie_title, movie_year, movie_url = get_imd_movie_info(movie)

        movie_summary = get_imd_summary(movie_url)

        print(movie_title, movie_year)

        print(movie_summary)

        print(""--------------------------------------------"")

        ctr=ctr+1

        if (ctr==10):

          break;   

if __name__ == '__main__':

    imd_movie_picker()

  ",0,WERESOURCE,NA,PYTHON

,"import json

from datetime import datetime



def replicate_json_file(source_filename, destination_filename):

    try:

        # 1. Open and read the existing JSON file

        with open(source_filename, 'r', encoding='utf-8') as source_file:

            data = json.load(source_file)

        

        # 2. (Optional) Modify the data

        # For example, let's add metadata about when this copy was created
        if isinstance(data, dict):
            data['processed_at'] = datetime.now().strftime(""%Y-%m-%d %H:%M:%S"")
            data['status'] = ""replicated""

        # 3. Write the data to a new JSON file
        with open(destination_filename, 'w', encoding='utf-8') as dest_file:
            # indent=4 makes the new file human-readable
            json.dump(data, dest_file, indent=4, sort_keys=True)
            
        print(f""Successfully created '{destination_filename}' from '{source_filename}'."")

    except FileNotFoundError:
        print(""Error: The source file does not exist."")
    except json.JSONDecodeError:
        print(""Error: Failed to decode JSON. Check if the source file is valid."")
    except Exception as e:
        print(f""An unexpected error occurred: {e}"")

# --- Usage ---
# Ensure you have a file named 'source.json' in your directory before running
replicate_json_file('source.json', 'new_backup.json')",1,GEMINI,Write a Python program to create a new JSON file from an existing JSON file.,PYTHON
,"#https://bit.ly/2lVhlLX
# landing page:
# http://earthquake.usgs.gov/earthquakes/feed/v1.0/csv.php
import csv
import requests
csvurl = 'http://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/4.5_month.csv'
rows = list(csv.DictReader(requests.get(csvurl).text.splitlines()))
print(""The number of magnitude 4.5+ earthquakes detected worldwide by the USGS:"", len(rows))
  ",0,WERESOURCE,NA,PYTHON
,"def check_if_complex(data):
    """"""
    Checks if the provided data instance is of the complex type.
    """"""
    if isinstance(data, complex):
        print(f""✓ {data} is a complex number."")
        print(f""  - Real part: {data.real}"")
        print(f""  - Imaginary part: {data.imag}"")
    else:
        print(f""✗ {data} (type: {type(data).__name__}) is NOT a complex number."")

# --- Testing various instances ---

# A standard complex number
val1 = 5 + 3j

# A complex number created via constructor
val2 = complex(10, -2)

# A standard integer
val3 = 100

# A float
val4 = 7.5

print(""Starting Instance Check:\n"" + ""-""*25)
check_if_complex(val1)
check_if_complex(val2)
check_if_complex(val3)
check_if_complex(val4)",1,GEMINI,Write a Python program to check whether an instance is complex or not.,PYTHON
,"import requests
response = requests.get('https://python.org')
print(""Status Code: "",response.status_code)
print(""Headers: "",response.headers)
print(""Url: "",response.url)
print(""History: "",response.history)
print(""Encoding: "",response.encoding)
print(""Reason: "",response.reason)
print(""Cookies: "",response.cookies)
print(""Elapsed: "",response.elapsed)
print(""Request: "",response.request)
print(""Content: "",response._content)
  ",0,WERESOURCE,NA,PYTHON
,"import json

def has_complex_structure(data):
    """"""
    Recursively checks if a Python object contains nested 
    collections (dict or list).
    """"""
    # If the root is a list, check its elements
    if isinstance(data, list):
        for item in data:
            if isinstance(item, (dict, list)):
                return True
        return False

    # If the root is a dict, check if any value is a dict or list
    if isinstance(data, dict):
        for value in data.values():
            if isinstance(value, (dict, list)):
                return True
    
    return False

def check_json_complexity(json_str):
    try:
        parsed = json.loads(json_str)
        if has_complex_structure(parsed):
            print(""Complexity Found: This JSON contains nested objects/arrays."")
        else:
            print(""Simple JSON: This is a flat key-value structure."")
    except json.JSONDecodeError:
        print(""Invalid JSON string."")

# --- Test Cases ---

simple_json = '{""name"": ""Alice"", ""age"": 30}'
complex_json = '{""user"": {""id"": 1, ""name"": ""Alice""}, ""tags"": [""admin"", ""dev""]}'

print(""Checking simple_json:"")
check_json_complexity(simple_json)

print(""\nChecking complex_json:"")
check_json_complexity(complex_json)",1,GEMINI,Write a Python program to check whether a JSON string contains complex object or not,PYTHON
,"import requests
print(requests.get('https://w3resource.com'))
print(requests.get('https://wayback.com'))
  ",0,WERESOURCE,NA,PYTHON
,"def get_unique_values(data_obj):
    # We use set() because sets automatically remove duplicates
    unique_values = set(data_obj.values())
    return list(unique_values)

# Example: Several keys share the same value
employee_roles = {
    ""Alice"": ""Engineer"",
    ""Bob"": ""Manager"",
    ""Charlie"": ""Engineer"",
    ""David"": ""Intern"",
    ""Eve"": ""Manager""
}

print(f""Unique Roles: {get_unique_values(employee_roles)}"")",1,GEMINI,Write a Python program to access only unique key value of a Python object.,PYTHON
,"public class OddEvenArray
{
public static void main(String args[])
{
int s, i;
int[] a = { 33, 2, 4, 71, 88, 92, 9, 1 };
for (i = 0; i < a.length; i++)
{
for (int j = i + 1; j < a.length; j++)
{
if (a[i] > a[j])
{
s = a[i];
a[i] = a[j];
a[j] = s;
}

}
}
System.out.print(""Input numbers :"");
for (i = 0; i < a.length; i++)
{
System.out.print("" "" + a[i]);
}
System.out.print(""\nOdd numbers :"");
for (i = 0; i <= a.length - 1; i++)
{
if (a[i] % 2 != 0)
{
System.out.print("" "" + a[i]);
}
}
System.out.print(""\nEven numbers :"");
for (i = 0; i < a.length; i++)
{
if (a[i] % 2 == 0)
{
System.out.print("" "" + a[i]);
}
}
}
}
",0,IPSGWALIOR.ORG,NA,JAVA
,"public List<List<String>> groupAnagrams(String[] strs) {
    Map<String, List<String>> map = new HashMap<>();
    for (String s : strs) {
        char[] ca = s.toCharArray();
        Arrays.sort(ca);
        String key = String.valueOf(ca);
        map.computeIfAbsent(key, k -> new ArrayList<>()).add(s);
    }
    return new ArrayList<>(map.values());
}",1,GEMINI,"Given an array of strings, group anagrams together.",JAVA
,"class MatrixAddition
{
public static void main(String args[])
{
int[][] a = new int[][] { { 1, 2, 3},{ 4, 5, 6},{ 7, 8, 9} };

int[][] b = new int[][] { { 10, 11, 12},{ 13, 14, 15},{ 16, 17, 18} };
int[][] c = new int[3][3];
if(a.length == b.length && a[0].length == b[0].length)
{
for(int i = 0;i < a.length;i++)
{
for(int j = 0;j < a[i].length;j++)
{
c[i][j] = a[i][j] + b[i][j];
}
}
}
else
{
System.out.println(""'A' and 'B' Matrix are not SAME"");
return;
}
System.out.println(""The Matrix 'A' Value:"");
for(int i = 0;i < a.length;i++)
{
for(int j = 0;j < a[i].length;j++)
{
System.out.print(a[i][j] + "" "");
}
System.out.println();
}

System.out.println(""The Matrix 'B' Value:"");
for(int i = 0;i < a.length;i++)
{
for(int j = 0;j < a[i].length;j++)
{
System.out.print(b[i][j]+ "" "");
 }
System.out.println();
}
 System.out.println(""The Addition Matrix of 'A' and 'B' Value:"");
for(int i = 0;i < a.length;i++)
{
for(int j = 0;j < a[i].length;j++)
{
System.out.print(c[i][j] + "" "");
}
System.out.println();
}
}
}",0,IPSGWALIOR.ORG,NA,JAVA
,"class LRUCache extends LinkedHashMap<Integer, Integer> {
    private final int capacity;
    public LRUCache(int capacity) {
        super(capacity, 0.75f, true);
        this.capacity = capacity;
    }
    protected boolean removeEldestEntry(Map.Entry eldest) {
        return size() > capacity;
    }
}",1,GEMINI,Design a data structure that follows the constraints of a Least Recently Used (LRU) cache.,JAVA
,"class NullMatrix
{
public static void main(String args[])
{
int[][] a = new int[][] { { 0, 0, 0},{ 0, 0, 1},{ 0, 0, 0} };
boolean setValue = true;
abc: for(int i = 0;i < a.length;i++)
{
for(int j = 0;j < a[i].length;j++)
{
if(a[i][j] != 0)
{
setValue = false;
break abc;
}
}
}

System.out.println(""The Given Matrix Value:"");
for(int i = 0;i < a.length;i++)
{
for(int j = 0;j < a[i].length;j++)
{
System.out.print(a[i][j] + "" "");
}
System.out.println();
}
if(setValue == true)
{
System.out.println(""The Given Matrix is a Null Matrix"");
}
else
{
System.out.println(""The Given Matrix is not a Null Matrix"");
}
}
}
",0,IPSGWALIOR.ORG,,JAVA
,"public int lengthOfLongestSubstring(String s) {
    int max = 0;
    Map<Character, Integer> map = new HashMap<>();
    for (int j = 0, i = 0; j < s.length(); j++) {
        if (map.containsKey(s.charAt(j))) i = Math.max(map.get(s.charAt(j)), i);
        max = Math.max(max, j - i + 1);
        map.put(s.charAt(j), j + 1);
    }
    return max;
}",1,GEMINI,Find the length of the longest substring without repeating characters.,JAVA
,"class DiagonalMatrix
 {
 public static void main(String args[])
 {
 int[][] a = new int[][] { { 1, 0, 1},{ 0, 3, 0},{ 0, 0, 3} };
 boolean setValue = true;
 abc: for(int i = 0;i < a.length;i++)
 {
 for(int j = 0;j < a[i].length;j++)
 {

 if(i == j)
 {
 if(a[i][j] == 0)
 {
 setValue = false;
 break abc;
 }
 }
 else if(a[i][j] != 0)
 {
 setValue = false;
 break abc;
 }
 }
 }

 System.out.println(""The Given Matrix Value:"");
 for(int i = 0;i < a.length;i++)
 {
 for(int j = 0;j < a[i].length;j++)
 {
 System.out.print(a[i][j] + "" "");
 }
 System.out.println();
 }

 if(setValue == true)
 {
 System.out.println(""The Given Matrix is a Diagonal Matrix"");
 }
 else
 {
 System.out.println(""The Given Matrix is not a Diagonal Matrix"");
 }
 }
 }
",0,IPSGWALIOR.ORG,NA,JAVA
,"class MinStack {
    private Stack<Integer> st = new Stack<>(), minSt = new Stack<>();
    public void push(int x) {
        st.push(x);
        if (minSt.isEmpty() || x <= minSt.peek()) minSt.push(x);
    }
    public void pop() {
        if (st.pop().equals(minSt.peek())) minSt.pop();
    }
    public int getMin() { return minSt.peek(); }
}",1,GEMINI,"Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.",JAVA
,"import java.util.Scanner;
class LinearSearch
{
public static void main(String args[])
{
int i, num, searchval, array[];
Scanner in = new Scanner(System.in);
System.out.println(""Enter number of elements"");
num = in.nextInt();
array = new int[num];
System.out.println(""Enter "" + num + "" integers"");

for (i = 0; i < num; i++)
array[i] = in.nextInt();
System.out.println(""Enter the search value:"");
searchval = in.nextInt();
in.close();
for (i = 0; i < num; i++)
{
if (array[i] == searchval)
{
System.out.println(searchval + "" is present at location "" + (i + 1));
break;
}
}
if (i == num)
System.out.println(searchval + "" is not exist in array."");
}
",0,IPSGWALIOR.ORG,NA,JAVA
,"public int findKthLargest(int[] nums, int k) {
    PriorityQueue<Integer> pq = new PriorityQueue<>();
    for (int val : nums) {
        pq.offer(val);
        if (pq.size() > k) pq.poll();
    }
    return pq.peek();
}",1,GEMINI,Find the kth largest element in an unsorted array.,JAVA
,"import java.util.Scanner;
public class BinarySearch
{
public static void main(String args[])
{
int counter, num, item, array[], first, last, middle;
Scanner input = new Scanner(System.in);
System.out.println(""Enter number of elements:"");
num = input.nextInt();
array = new int[num];
System.out.println(""Enter "" + num + "" integers"");
for (counter = 0; counter < num; counter++)
array[counter] = input.nextInt();
System.out.println(""Enter the search value:"");
item = input.nextInt();
first = 0;
last = num - 1;
middle = (first + last) / 2;
while (first <= last)
{
if (array[middle] < item)
first = middle + 1;
else if (array[middle] == item)
{
System.out.println(item + "" found at location "" + (middle + 1) + ""."");
break;

}
else
{
last = middle - 1;
}
middle = (first + last) / 2;
}
if (first > last)
System.out.println(item + "" is not found.\n"");
}
}
",0,IPSGWALIOR.ORG,NA,JAVA
,"public ListNode mergeKLists(ListNode[] lists) {
    PriorityQueue<ListNode> pq = new PriorityQueue<>((a, b) -> a.val - b.val);
    for (ListNode l : lists) if (l != null) pq.add(l);
    ListNode dummy = new ListNode(0), tail = dummy;
    while (!pq.isEmpty()) {
        tail.next = pq.poll();
        tail = tail.next;
        if (tail.next != null) pq.add(tail.next);
    }
    return dummy.next;
}",1,GEMINI,write a program to Merge k sorted linked lists into one sorted linked list.,JAVA
,"public class FindHCFAndLCM
{
public static void main(String args[])
{
int a, b, x, y, t, hcf, lcm;
x = 6;
y = 10;
a = x;
b = y;
while (b != 0)
{
t = b;
b = a % b;
a = t;
}
hcf = a;
lcm = (x * y) / hcf;
System.out.print(""HCF and LCM of : "" + x + "" and "" + y + "" is :\n"");
System.out.print(""HCF = "" + hcf);
System.out.print(""\nLCM = "" + lcm);
}
}
",0,IPSGWALIOR.ORG,NA,JAVA
,"public int trap(int[] height) {
    int l = 0, r = height.length - 1, lMax = 0, rMax = 0, ans = 0;
    while (l < r) {
        if (height[l] < height[r]) {
            if (height[l] >= lMax) lMax = height[l]; else ans += lMax - height[l];
            l++;
        } else {
            if (height[r] >= rMax) rMax = height[r]; else ans += rMax - height[r];
            r--;
        }
    }
    return ans;
}",1,GEMINI,"write a java progrom for Given n non-negative integers representing an elevation map, compute how much water it can trap.",JAVA
,"public class Cube {
public static void main(String arg[]) {
int side=5;
float volume=side * side * side;
System.out.println(""Volume of Cube :""+ volume);
}
}
",0,IPSGWALIOR.ORG,NA,JAVA
,"public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
    if (root == null || root == p || root == q) return root;
    TreeNode left = lowestCommonAncestor(root.left, p, q);
    TreeNode right = lowestCommonAncestor(root.right, p, q);
    return left == null ? right : right == null ? left : root;
}",1,GEMINI,Find the lowest common ancestor of two given nodes in a tree.,JAVA
,"public class ReverseNum
{
public static void main(String[] args)
{

int rev = 0;
int num = 1234;
int no=num;
while (num > 0)
{
int rem = num % 10;
rev = rem + (rev * 10);
num = num / 10;
}
System.out.println(""Number = ""+no);
System.out.println(""Reverse = ""+rev);
}
}",0,IPSGWALIOR.ORG,NA,JAVA
,"public int ladderLength(String begin, String end, List<String> wordList) {
    Set<String> set = new HashSet<>(wordList);
    Queue<String> q = new LinkedList<>(); q.add(begin);
    int step = 1;
    while (!q.isEmpty()) {
        int size = q.size();
        for (int i = 0; i < size; i++) {
            char[] cur = q.poll().toCharArray();
            for (int j = 0; j < cur.length; j++) {
                char tmp = cur[j];
                for (char c = 'a'; c <= 'z'; c++) {
                    cur[j] = c; String next = new String(cur);
                    if (set.contains(next)) {
                        if (next.equals(end)) return step + 1;
                        q.add(next); set.remove(next);
                    }
                }
                cur[j] = tmp;
            }
        }
        step++;
    }
    return 0;
}",1,GEMINI,give me an java program to Find the length of shortest transformation sequence from beginWord to endWord.,JAVA
,"import java.util.HashMap;
import java.util.Scanner;
public class IntegertoRoman
{
private static int[] bases = { 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1 };
private static HashMap<Integer, String> map = new HashMap<Integer, String>();
private static void setup()
{
map.put(1, ""I"");
map.put(4, ""IV"");
map.put(5, ""V"");
map.put(9, ""IX"");
map.put(10, ""X"");
map.put(40, ""XL"");
map.put(50, ""L"");
map.put(90, ""XC"");
map.put(100, ""C"");
map.put(400, ""CD"");
map.put(500, ""D"");
map.put(900, ""CM"");
map.put(1000, ""M"");
}
public String intToRoman(int num)
{
setup();
String result = new String();
for (int i : bases)
{
while (num >= i)
{

result += map.get(i);
num -= i;
}
}
return result;
}
public static void main(String arg[])
{
System.out.println(""Enter the number : "");
Scanner sc = new Scanner(System.in);
int no = sc.nextInt();
IntegertoRoman in = new IntegertoRoman();
int value=no;
String sd = in.intToRoman(value);
System.out.println(value+"" ---> "" + sd);
}
}
",0,IPSGWALIOR.ORG,NA,JAVA
,"public class Singleton {
    private static volatile Singleton instance;
    public static Singleton getInstance() {
        if (instance == null) {
            synchronized (Singleton.class) {
                if (instance == null) instance = new Singleton();
            }
        }
        return instance;
    }
}",1,GEMINI,write a program to Implement a thread-safe Singleton that prevents unnecessary synchronization.,JAVA
,"public class WordCount
{
public static void main(String args[])
{
String s = ""welcome to candid java tutorial"";
int count = 1;
for (int i = 0; i < s.length() - 1; i++)
{
if ((s.charAt(i) == ' ') && (s.charAt(i + 1) != ' '))
{
count++;
}
}
System.out.println(""Number of words in a string = "" + count);
}
",0,IPSGWALIOR.ORG,NA,JAVA
,"class PC {
    LinkedList<Integer> list = new LinkedList<>();
    public void produce() throws InterruptedException {
        synchronized(this) {
            while (list.size() == 1) wait();
            list.add(1); notify();
        }
    }
    public void consume() throws InterruptedException {
        synchronized(this) {
            while (list.isEmpty()) wait();
            list.removeFirst(); notify();
        }
    }
}",1,GEMINI,give me a java program to Implement the Producer-Consumer pattern using wait() and notify(),JAVA
,"public class CountWords
{
public static void main(String[] args)
{
String input=""Welcome to Java Session Session Session"";
String[] words=input.split("" "");
int wrc=1;
for(int i=0;i<words.length;i++)
{

for(int j=i+1;j<words.length;j++)
{
if(words[i].equals(words[j]))
{
wrc=wrc+1;
words[j]=""0"";
}
}
if(words[i]!=""0"")
System.out.println(words[i]+""--""+wrc);
wrc=1;
 }
}
}",0,IPSGWALIOR.ORG,NA,JAVA
,"public void deadlock() {
    String r1 = ""r1"", r2 = ""r2"";
    new Thread(() -> { synchronized(r1) { synchronized(r2) {} } }).start();
    new Thread(() -> { synchronized(r2) { synchronized(r1) {} } }).start();
}",1,GEMINI,Write a Java program that results in a deadlock.,JAVA
,"public class RemoveDuplicate
{
public static void main(String[] args)
{
String input=""Welcome to Java Session Java Session Session Java"";
String[] words=input.split("" "");
for(int i=0;i<words.length;i++)
{
if(words[i]!=null)
{
for(int j=i+1;j<words.length;j++)
{
if(words[i].equals(words[j]))
{
words[j]=null;
}
}
}
}
for(int k=0;k<words.length;k++)
{
if(words[k]!=null)
{
System.out.println(words[k]);
}
 }
}
}",0,IPSGWALIOR.ORG,NA,JAVA
,"public int trap(int[] height) {
    int l = 0, r = height.length - 1, lMax = 0, rMax = 0, trapped = 0;
    while (l < r) {
        if (height[l] < height[r]) {
            if (height[l] >= lMax) lMax = height[l]; else trapped += lMax - height[l++];
        } else {
            if (height[r] >= rMax) rMax = height[r]; else trapped += rMax - height[r--];
        }
    }
    return trapped;
}",1,GEMINI,"write an effective java code for a Given elevation map (array), calculate how much water it can trap after raining. Use a two-pointer approach for $O(n)$ time and $O(1)$ space.",JAVA
,"import java.io.IOException;

 public class FindTtalCountWords
 {

 public static void main(String args[]) throws IOException
 {
 countWords(""apple banna apple fruit fruit apple hello hi hi hello hi"");

 }

 static void countWords(String st)
 {
 String[] words = st.split(""\\s"");
 int[] fr = new int[words.length];
 for (int i = 0; i < fr.length; i++)
 fr[i] = 0;
 for (int i = 0; i < words.length; i++)
 {
 for (int j = 0; j < words.length; j++)
 {
 if (words[i].equals(words[j]))
 {

 fr[i]++;

 }
 }
 }

 for (int i = 0; i < words.length; i++)
 {
 for (int j = 0; j < words.length; j++)
 {
 if (words[i].equals(words[j]))
 {
 if (i != j)
 {
 words[i] = """";
 }
 }
 }
 }

 int total = 0;
 System.out.println(""Words and words count:"");
 for (int i = 0; i < words.length; i++)
 {
 if (words[i] != """")
 {

 System.out.println(words[i] + ""="" + fr[i]);

 total += fr[i];

 }
 }
 System.out.println(""Total words counted: "" + total);
 }
 }
",0,IPSGWALIOR.ORG,NA,JAVA
,"class Printer {
    boolean oddTurn = true;
    synchronized void print(int n, boolean isOdd) throws Exception {
        while (oddTurn != isOdd) wait();
        System.out.println(n);
        oddTurn = !isOdd;
        notifyAll();
    }
}
// Logic: Thread 1 calls print(i, true), Thread 2 calls print(i, false)",1,GEMINI,Create two threads—one printing odd numbers and one even—ensuring they print in perfect sequence up to $N$.,JAVA
,"public class PalindromeChecking
{
public static void main(String[] args)
{
String inpstr =""AMMA"";
char[] inpArray = inpstr.toCharArray();
char[] revArray = new char[inpArray.length];
int j=0;
for (int i = inpArray.length - 1; i >= 0; i--) {
revArray[j]=inpArray[i];
j++;
}
String revstr=String.valueOf(revArray);
if(inpstr.equals(revstr))
{
System.out.println(""The given string is a Palindrome"");
}
else
{
System.out.println(""The given string is not a Palindrome"");
}
}
}
",0,IPSGWALIOR.ORG,NA,JAVA
,"public List<String> flattenAndProcess(List<List<String>> nested) {
    return nested.stream()
            .flatMap(Collection::stream)
            .map(String::toUpperCase)
            .distinct()
            .collect(Collectors.toList());
}",1,GEMINI,"Write a Java Stream pipeline to flatten a List<List<String>> into a single list of uppercase strings, removing duplicates.",JAVA
,"public class RemoveAllVovels {

 public static void main(String[] args) {
 String string = ""Welcome to Candid Java Programming"";
 System.out.println(""Input String : ""+string);
 string = string.replaceAll(""[AaEeIiOoUu]"", """");
 System.out.println(string);
 }
 }
",0,IPSGWALIOR.ORG,NA,JAVA
,"public List<List<Integer>> threeSum(int[] nums) {
    Arrays.sort(nums);
    List<List<Integer>> res = new ArrayList<>();
    for (int i = 0; i < nums.length - 2 && nums[i] <= 0; i++) {
        if (i > 0 && nums[i] == nums[i-1]) continue;
        int l = i + 1, r = nums.length - 1;
        while (l < r) {
            int sum = nums[i] + nums[l] + nums[r];
            if (sum < 0) l++;
            else if (sum > 0) r--;
            else {
                res.add(Arrays.asList(nums[i], nums[l++], nums[r--]));
                while (l < r && nums[l] == nums[l-1]) l++;
            }
        }
    }
    return res;
}",1,GEMINI,Find all unique triplets in an array that sum to zero. Avoid duplicate triplets in the output.,JAVA
,"public class StringCapital
 {
 public static void main(String[] args)
 {
 String str = ""welcome to candid java program"";
 StringBuilder result = new StringBuilder(str.length());

 String words[] = str.split(""\\ "");
 for (int i = 0; i < words.length; i++)
 {

result.append(Character.toUpperCase(words[i].charAt(0))).append(words[i].substring(1)).append
("" "");

 }

 System.out.println(result);


 }

 }",0,IPSGWALIOR.ORG,NA,JAVA
,"import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class ThreadSafeLRUCache<K, V> {
    private final int capacity;
    private final ConcurrentHashMap<K, Node<K, V>> cache;
    private final DoublyLinkedList<K, V> dll;
    private final ReentrantReadWriteLock lock;
    
    private static class Node<K, V> {
        K key;
        V value;
        Node<K, V> prev;
        Node<K, V> next;
        
        Node(K key, V value) {
            this.key = key;
            this.value = value;
        }
    }
    
    private static class DoublyLinkedList<K, V> {
        private Node<K, V> head;
        private Node<K, V> tail;
        
        void addToFront(Node<K, V> node) {
            if (head == null) {
                head = tail = node;
            } else {
                node.next = head;
                head.prev = node;
                head = node;
            }
        }
        
        void remove(Node<K, V> node) {
            if (node.prev != null) {
                node.prev.next = node.next;
            } else {
                head = node.next;
            }
            
            if (node.next != null) {
                node.next.prev = node.prev;
            } else {
                tail = node.prev;
            }
            
            node.prev = node.next = null;
        }
        
        Node<K, V> removeLast() {
            if (tail == null) return null;
            Node<K, V> last = tail;
            remove(last);
            return last;
        }
        
        void moveToFront(Node<K, V> node) {
            remove(node);
            addToFront(node);
        }
    }
    
    public ThreadSafeLRUCache(int capacity) {
        this.capacity = capacity;
        this.cache = new ConcurrentHashMap<>();
        this.dll = new DoublyLinkedList<>();
        this.lock = new ReentrantReadWriteLock();
    }
    
    public V get(K key) {
        lock.readLock().lock();
        try {
            Node<K, V> node = cache.get(key);
            if (node == null) return null;
            
            lock.readLock().unlock();
            lock.writeLock().lock();
            try {
                dll.moveToFront(node);
                return node.value;
            } finally {
                lock.readLock().lock();
                lock.writeLock().unlock();
            }
        } finally {
            lock.readLock().unlock();
        }
    }
    
    public void put(K key, V value) {
        lock.writeLock().lock();
        try {
            Node<K, V> node = cache.get(key);
            
            if (node != null) {
                node.value = value;
                dll.moveToFront(node);
            } else {
                node = new Node<>(key, value);
                
                if (cache.size() >= capacity) {
                    Node<K, V> removed = dll.removeLast();
                    if (removed != null) {
                        cache.remove(removed.key);
                    }
                }
                
                cache.put(key, node);
                dll.addToFront(node);
            }
        } finally {
            lock.writeLock().unlock();
        }
    }
    
    public int size() {
        lock.readLock().lock();
        try {
            return cache.size();
        } finally {
            lock.readLock().unlock();
        }
    }
}",1,DEEPSEEK,Design and implement a thread-safe Least Recently Used (LRU) cache with O(1) average time complexity for get and put operations. The cache should have a fixed capacity and evict the least recently used item when capacity is reached.,JAVA
,"public class CommaSeparated
{
public static void main(String[] args)
{
String input=""Welcome,to,Java Session Session Session"";
String[] words=input.split("","");
for(int k=0;k<words.length;k++)
{
System.out.println(words[k]);
 }
}
}",0,IPSGWALIOR.ORG,NA,JAVA
,"import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

public class TokenBucketRateLimiter {
    private final long capacity;
    private final long refillTokensPerSecond;
    private long availableTokens;
    private long lastRefillTimestamp;
    private final ReentrantLock lock;
    
    public TokenBucketRateLimiter(long capacity, long refillTokensPerSecond) {
        this.capacity = capacity;
        this.refillTokensPerSecond = refillTokensPerSecond;
        this.availableTokens = capacity;
        this.lastRefillTimestamp = System.currentTimeMillis();
        this.lock = new ReentrantLock();
    }
    
    public boolean tryAcquire() {
        return tryAcquire(1);
    }
    
    public boolean tryAcquire(long tokens) {
        if (tokens <= 0 || tokens > capacity) {
            throw new IllegalArgumentException(""Invalid token request"");
        }
        
        lock.lock();
        try {
            refillTokens();
            
            if (availableTokens >= tokens) {
                availableTokens -= tokens;
                return true;
            }
            return false;
        } finally {
            lock.unlock();
        }
    }
    
    public boolean tryAcquireWithTimeout(long tokens, long timeout, TimeUnit unit) 
            throws InterruptedException {
        long timeoutMillis = unit.toMillis(timeout);
        long startTime = System.currentTimeMillis();
        
        while (System.currentTimeMillis() - startTime < timeoutMillis) {
            if (tryAcquire(tokens)) {
                return true;
            }
            
            // Calculate wait time for next token
            lock.lock();
            try {
                refillTokens();
                if (availableTokens < tokens && refillTokensPerSecond > 0) {
                    long tokensNeeded = tokens - availableTokens;
                    long waitTimeMillis = (tokensNeeded * 1000) / refillTokensPerSecond;
                    Thread.sleep(Math.min(waitTimeMillis, 100));
                }
            } finally {
                lock.unlock();
            }
        }
        return false;
    }
    
    private void refillTokens() {
        long now = System.currentTimeMillis();
        long timeElapsed = now - lastRefillTimestamp;
        
        if (timeElapsed > 0) {
            long tokensToAdd = (timeElapsed * refillTokensPerSecond) / 1000;
            
            if (tokensToAdd > 0) {
                availableTokens = Math.min(capacity, availableTokens + tokensToAdd);
                lastRefillTimestamp = now;
            }
        }
    }
    
    public long getAvailableTokens() {
        lock.lock();
        try {
            refillTokens();
            return availableTokens;
        } finally {
            lock.unlock();
        }
    }
}",1,DEEPSEEK,Implement a thread-safe rate limiter using the token bucket algorithm that allows a maximum of N requests per second.,JAVA
,"public class AsciiToCharacter
{
public static void main(String[] args)
{
char c;
for(int i=65;i<=90;i++)
{
c =(char)i;
System.out.println(i+"" = ""+c);
}
}
}",0,IPSGWALIOR.ORG,NA,JAVA
,"import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class CircularBuffer<T> {
    private final T[] buffer;
    private final int capacity;
    private int head;
    private int tail;
    private int count;
    private final ReentrantLock lock;
    private final Condition notEmpty;
    private final Condition notFull;
    private volatile boolean isShutdown;
    
    @SuppressWarnings(""unchecked"")
    public CircularBuffer(int capacity) {
        this.capacity = capacity;
        this.buffer = (T[]) new Object[capacity];
        this.lock = new ReentrantLock();
        this.notEmpty = lock.newCondition();
        this.notFull = lock.newCondition();
        this.isShutdown = false;
    }
    
    public boolean put(T item) throws InterruptedException {
        return put(item, -1);
    }
    
    public boolean put(T item, long timeoutMillis) throws InterruptedException {
        if (item == null) throw new NullPointerException();
        
        lock.lock();
        try {
            // Wait until buffer is not full or shutdown
            while (count == capacity && !isShutdown) {
                if (timeoutMillis <= 0) {
                    notFull.await();
                } else {
                    if (!notFull.await(timeoutMillis, java.util.concurrent.TimeUnit.MILLISECONDS)) {
                        return false;
                    }
                }
            }
            
            if (isShutdown) return false;
            
            buffer[tail] = item;
            tail = (tail + 1) % capacity;
            count++;
            notEmpty.signal();
            return true;
        } finally {
            lock.unlock();
        }
    }
    
    public T take() throws InterruptedException {
        return take(-1);
    }
    
    public T take(long timeoutMillis) throws InterruptedException {
        lock.lock();
        try {
            // Wait until buffer is not empty or shutdown
            while (count == 0 && !isShutdown) {
                if (timeoutMillis <= 0) {
                    notEmpty.await();
                } else {
                    if (!notEmpty.await(timeoutMillis, java.util.concurrent.TimeUnit.MILLISECONDS)) {
                        return null;
                    }
                }
            }
            
            if (count == 0 && isShutdown) return null;
            
            T item = buffer[head];
            buffer[head] = null; // Help GC
            head = (head + 1) % capacity;
            count--;
            notFull.signal();
            return item;
        } finally {
            lock.unlock();
        }
    }
    
    public boolean offer(T item) {
        if (item == null) throw new NullPointerException();
        
        lock.lock();
        try {
            if (count == capacity || isShutdown) {
                return false;
            }
            
            buffer[tail] = item;
            tail = (tail + 1) % capacity;
            count++;
            notEmpty.signal();
            return true;
        } finally {
            lock.unlock();
        }
    }
    
    public T poll() {
        lock.lock();
        try {
            if (count == 0) {
                return null;
            }
            
            T item = buffer[head];
            buffer[head] = null;
            head = (head + 1) % capacity;
            count--;
            notFull.signal();
            return item;
        } finally {
            lock.unlock();
        }
    }
    
    public int size() {
        lock.lock();
        try {
            return count;
        } finally {
            lock.unlock();
        }
    }
    
    public boolean isEmpty() {
        lock.lock();
        try {
            return count == 0;
        } finally {
            lock.unlock();
        }
    }
    
    public boolean isFull() {
        lock.lock();
        try {
            return count == capacity;
        } finally {
            lock.unlock();
        }
    }
    
    public void shutdown() {
        lock.lock();
        try {
            isShutdown = true;
            notEmpty.signalAll();
            notFull.signalAll();
        } finally {
            lock.unlock();
        }
    }
    
    public void clear() {
        lock.lock();
        try {
            for (int i = 0; i < capacity; i++) {
                buffer[i] = null;
            }
            head = tail = count = 0;
            notFull.signalAll();
        } finally {
            lock.unlock();
        }
    }
}",1,DEEPSEEK,Implement a thread-safe circular buffer (ring buffer) with fixed capacity that supports concurrent producers and consumers.,JAVA
,"public class VowelswithStar
{

public static void main(String[] args)
{
String string = ""Welcome to Candid Java Programming""; //Input String
System.out.println(""Input String : ""+string); //Displaying Input String
string = string.replaceAll(""[AaEeIiOoUu]"", ""*""); //Replace vowels with star
System.out.println(string); //Display the word after replacement
}
}
",0,IPSGWALIOR.ORG,NA,JAVA
,"import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.atomic.AtomicInteger;

public class NonBlockingStack<T> {
    private static class Node<T> {
        final T value;
        Node<T> next;
        
        Node(T value) {
            this.value = value;
        }
    }
    
    private final AtomicReference<Node<T>> top = new AtomicReference<>();
    private final AtomicInteger size = new AtomicInteger(0);
    private final AtomicInteger operationCount = new AtomicInteger(0);
    
    public void push(T value) {
        Node<T> newHead = new Node<>(value);
        Node<T> oldHead;
        
        do {
            oldHead = top.get();
            newHead.next = oldHead;
        } while (!top.compareAndSet(oldHead, newHead));
        
        size.incrementAndGet();
        operationCount.incrementAndGet();
    }
    
    public T pop() {
        Node<T> oldHead;
        Node<T> newHead;
        
        do {
            oldHead = top.get();
            if (oldHead == null) {
                return null;
            }
            newHead = oldHead.next;
        } while (!top.compareAndSet(oldHead, newHead));
        
        size.decrementAndGet();
        operationCount.incrementAndGet();
        return oldHead.value;
    }
    
    public T peek() {
        Node<T> currentTop = top.get();
        return currentTop != null ? currentTop.value : null;
    }
    
    public boolean isEmpty() {
        return top.get() == null;
    }
    
    public int size() {
        return size.get();
    }
    
    public int getOperationCount() {
        return operationCount.get();
    }
    
    // Optimistic traversal for size (not thread-safe for exact count)
    public int optimisticSize() {
        int count = 0;
        Node<T> current = top.get();
        while (current != null) {
            count++;
            current = current.next;
        }
        return count;
    }
}",1,DEEPSEEK,Implement a thread-safe non-blocking stack using atomic operations (Treiber's algorithm).,JAVA
,"public class LetterPositionCount
 {

 public static void main(String args[])
 {

 String s = ""CANDIDJAVA"";
 char[] a = s.toCharArray();
 int i = 1;
 {
 for (char output : a)
 {

 System.out.print(output + "" "" + i + "" "");
 i++;

 }
 }

 }
 }
",0,IPSGWALIOR.ORG,NA,JAVA
,"import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class CustomThreadPool {
    private final BlockingQueue<Runnable> taskQueue;
    private final WorkerThread[] workers;
    private volatile boolean isShutdown;
    private final ReentrantLock mainLock = new ReentrantLock();
    private final Condition termination = mainLock.newCondition();
    private final AtomicInteger activeWorkers = new AtomicInteger(0);
    private final ThreadFactory threadFactory;
    
    private class WorkerThread extends Thread {
        private volatile Runnable currentTask;
        private volatile boolean stopped;
        
        public WorkerThread(String name) {
            super(name);
        }
        
        @Override
        public void run() {
            activeWorkers.incrementAndGet();
            
            try {
                while (!stopped && !isShutdown) {
                    try {
                        // Poll with timeout to allow graceful shutdown
                        Runnable task = taskQueue.poll(100, TimeUnit.MILLISECONDS);
                        
                        if (task != null) {
                            currentTask = task;
                            try {
                                task.run();
                            } catch (RuntimeException e) {
                                System.err.println(""Task execution failed: "" + e.getMessage());
                            } finally {
                                currentTask = null;
                            }
                        }
                    } catch (InterruptedException e) {
                        // Thread interrupted, check if we should exit
                        if (stopped || isShutdown) {
                            break;
                        }
                    }
                }
            } finally {
                activeWorkers.decrementAndGet();
                signalIfTerminated();
            }
        }
        
        public void stopWorker() {
            this.stopped = true;
            this.interrupt();
        }
        
        public Runnable getCurrentTask() {
            return currentTask;
        }
    }
    
    public CustomThreadPool(int poolSize) {
        this(poolSize, Executors.defaultThreadFactory());
    }
    
    public CustomThreadPool(int poolSize, ThreadFactory threadFactory) {
        if (poolSize <= 0) {
            throw new IllegalArgumentException(""Pool size must be positive"");
        }
        
        this.taskQueue = new LinkedBlockingQueue<>();
        this.workers = new WorkerThread[poolSize];
        this.threadFactory = threadFactory;
        this.isShutdown = false;
        
        // Initialize workers
        for (int i = 0; i < poolSize; i++) {
            WorkerThread worker = new WorkerThread(""CustomPool-Worker-"" + i);
            workers[i] = worker;
            worker.start();
        }
    }
    
    public void execute(Runnable task) {
        if (task == null) throw new NullPointerException();
        if (isShutdown) throw new RejectedExecutionException(""Thread pool is shutdown"");
        
        try {
            taskQueue.put(task);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            throw new RejectedExecutionException(""Interrupted while submitting task"", e);
        }
    }
    
    public Future<?> submit(Runnable task) {
        FutureTask<Void> future = new FutureTask<>(task, null);
        execute(future);
        return future;
    }
    
    public <T> Future<T> submit(Callable<T> task) {
        FutureTask<T> future = new FutureTask<>(task);
        execute(future);
        return future;
    }
    
    public void shutdown() {
        mainLock.lock();
        try {
            isShutdown = true;
        } finally {
            mainLock.unlock();
        }
    }
    
    public void shutdownNow() {
        mainLock.lock();
        try {
            isShutdown = true;
            
            // Clear task queue
            taskQueue.clear();
            
            // Interrupt all workers
            for (WorkerThread worker : workers) {
                if (worker != null) {
                    worker.stopWorker();
                }
            }
        } finally {
            mainLock.unlock();
        }
    }
    
    public boolean isShutdown() {
        return isShutdown;
    }
    
    public boolean isTerminated() {
        return isShutdown && activeWorkers.get() == 0 && taskQueue.isEmpty();
    }
    
    public boolean awaitTermination(long timeout, TimeUnit unit) 
            throws InterruptedException {
        long nanos = unit.toNanos(timeout);
        mainLock.lock();
        try {
            while (!isTerminated()) {
                if (nanos <= 0) {
                    return false;
                }
                nanos = termination.awaitNanos(nanos);
            }
            return true;
        } finally {
            mainLock.unlock();
        }
    }
    
    public int getActiveCount() {
        return activeWorkers.get();
    }
    
    public int getPoolSize() {
        return workers.length;
    }
    
    public long getTaskCount() {
        return taskQueue.size();
    }
    
    private void signalIfTerminated() {
        mainLock.lock();
        try {
            if (isTerminated()) {
                termination.signalAll();
            }
        } finally {
            mainLock.unlock();
        }
    }
}",1,DEEPSEEK,"Implement a custom thread pool executor with fixed thread count, task queue, and shutdown capabilities.",JAVA
,"public class ReverseWord
{
public static void main(String[] args)
{
String input=""Welcome to Java Session"";
String[] words=input.split("" "");
String[] revwords=new String[words.length];
int j=0;
for(int i=words.length-1;i>=0;i--)
 {
revwords[j]=words[i];
 System.out.print(revwords[j]+"" "");
j++;
}
}

}",0,IPSGWALIOR.ORG,NA,JAVA
,"import java.util.concurrent.locks.AbstractQueuedSynchronizer;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;

public class WriterPreferenceReadWriteLock implements ReadWriteLock {
    private final Sync sync;
    
    public WriterPreferenceReadWriteLock() {
        this.sync = new Sync();
    }
    
    private static class Sync extends AbstractQueuedSynchronizer {
        private static final int READER_MASK = (1 << 16) - 1;
        private static final int WRITER_MASK = ~READER_MASK;
        
        private int readers() {
            return getState() & READER_MASK;
        }
        
        private int writers() {
            return (getState() >>> 16) & READER_MASK;
        }
        
        private int incrementReaders() {
            return getState() + 1;
        }
        
        private int decrementReaders() {
            return getState() - 1;
        }
        
        private int incrementWriters() {
            return getState() + (1 << 16);
        }
        
        private int decrementWriters() {
            return getState() - (1 << 16);
        }
        
        @Override
        protected boolean tryAcquire(int arg) {
            Thread current = Thread.currentThread();
            int state = getState();
            
            // If no readers or writers, try to acquire write lock
            if (state == 0) {
                if (compareAndSetState(0, 1 << 16)) {
                    setExclusiveOwnerThread(current);
                    return true;
                }
            } else if (getExclusiveOwnerThread() == current) {
                // Reentrant write lock
                setState(state + (1 << 16));
                return true;
            }
            return false;
        }
        
        @Override
        protected boolean tryRelease(int arg) {
            if (getExclusiveOwnerThread() != Thread.currentThread()) {
                throw new IllegalMonitorStateException();
            }
            
            int newState = decrementWriters();
            boolean free = (newState & WRITER_MASK) == 0;
            
            if (free) {
                setExclusiveOwnerThread(null);
            }
            setState(newState);
            return free;
        }
        
        @Override
        protected int tryAcquireShared(int arg) {
            Thread current = Thread.currentThread();
            int state = getState();
            
            // If there are waiting writers, don't acquire read lock

            if (hasQueuedPredecessors()) {

                return -1;

            }

            

            // If no writers, try to acquire read lock

            if ((state & WRITER_MASK) == 0) {

                if (compareAndSetState(state, incrementReaders())) {

                    return 1;

                }

            }

            return -1;

        }

        

        @Override

        protected boolean tryReleaseShared(int arg) {

            int newState;

            int currentState;

            

            do {

                currentState = getState();

                newState = decrementReaders();

            } while (!compareAndSetState(currentState, newState));

            

            return true;

        }

        

        @Override

        protected boolean isHeldExclusively() {

            return getExclusiveOwnerThread() == Thread.currentThread();

        }

        

        Condition newCondition() {

            return new ConditionObject();

        }

    }

    

    private static class ReadLock implements Lock {

        private final Sync sync;

        

        ReadLock(Sync sync) {

            this.sync = sync;

        }

        

        @Override

        public void lock() {

            sync.acquireShared(1);

        }

        

        @Override

        public void lockInterruptibly() throws InterruptedException {

            sync.acquireSharedInterruptibly(1);

        }

        

        @Override

        public boolean tryLock() {

            return sync.tryAcquireShared(1) >= 0;

        }

        

        @Override

        public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {

            return sync.tryAcquireSharedNanos(1, unit.toNanos(time));

        }

        

        @Override

        public void unlock() {

            sync.releaseShared(1);

        }

        

        @Override

        public Condition newCondition() {

            throw new UnsupportedOperationException(""Read locks don't support conditions"");
        }
    }
    
    private static class WriteLock implements Lock {
        private final Sync sync;
        
        WriteLock(Sync sync) {
            this.sync = sync;
        }
        
        @Override
        public void lock() {
            sync.acquire(1);
        }
        
        @Override
        public void lockInterruptibly() throws InterruptedException {
            sync.acquireInterruptibly(1);
        }
        
        @Override
        public boolean tryLock() {
            return sync.tryAcquire(1);
        }
        
        @Override
        public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
            return sync.tryAcquireNanos(1, unit.toNanos(time));
        }
        
        @Override
        public void unlock() {
            sync.release(1);
        }
        
        @Override
        public Condition newCondition() {
            return sync.newCondition();
        }
    }
    
    @Override
    public Lock readLock() {
        return new ReadLock(sync);
    }
    
    @Override
    public Lock writeLock() {
        return new WriteLock(sync);
    }
}",1,DEEPSEEK,Implement a read-write lock that gives preference to writers to prevent writer starvation.,JAVA
,"public class StringReverse {

 public static void main(String args[])
 {
 String string = ""Welcome to Java Programming and Dotnet Programming"";
 String[] wordsCount = string.split("" "");

 System.out.println(""The Given String is:\n"" + string + ""\n"");
 System.out.println(""After Reverse String is:"");

 for(int i = wordsCount.length;i > 0;i--)
 {
 System.out.print(wordsCount[i - 1] + "" "");
 }
 }
 }",0,IPSGWALIOR.ORG,NA,JAVA
,"import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.ReentrantLock;

public class DistributedTaskScheduler {
    private final ExecutorService executor;
    private final List<WorkerNode> workerNodes;
    private final Map<String, ScheduledTask> tasks;
    private final AtomicInteger taskIdCounter;
    private final ReentrantLock lock;
    private final ScheduledExecutorService healthCheckScheduler;
    
    public static class WorkerNode {
        private final String id;
        private final String host;
        private final int port;
        private volatile boolean healthy;
        private volatile long lastHeartbeat;
        
        public WorkerNode(String id, String host, int port) {
            this.id = id;
            this.host = host;
            this.port = port;
            this.healthy = true;
            this.lastHeartbeat = System.currentTimeMillis();
        }
        
        // Getters and setters
        public String getId() { return id; }
        public String getHost() { return host; }
        public int getPort() { return port; }
        public boolean isHealthy() { return healthy; }
        public void setHealthy(boolean healthy) { this.healthy = healthy; }
        public long getLastHeartbeat() { return lastHeartbeat; }
        public void updateHeartbeat() { this.lastHeartbeat = System.currentTimeMillis(); }
    }
    
    public static class ScheduledTask {
        private final String id;
        private final Runnable task;
        private final long initialDelay;
        private final long period;
        private final TimeUnit timeUnit;
        private volatile TaskStatus status;
        private volatile String assignedWorker;
        private volatile Future<?> future;
        
        public ScheduledTask(String id, Runnable task, long initialDelay, 
                           long period, TimeUnit timeUnit) {
            this.id = id;
            this.task = task;
            this.initialDelay = initialDelay;
            this.period = period;
            this.timeUnit = timeUnit;
            this.status = TaskStatus.PENDING;
        }
        
        public enum TaskStatus {
            PENDING, SCHEDULED, RUNNING, COMPLETED, FAILED, CANCELLED
        }
        
        // Getters and setters
        public String getId() { return id; }
        public Runnable getTask() { return task; }
        public long getInitialDelay() { return initialDelay; }
        public long getPeriod() { return period; }
        public TimeUnit getTimeUnit() { return timeUnit; }
        public TaskStatus getStatus() { return status; }
        public void setStatus(TaskStatus status) { this.status = status; }
        public String getAssignedWorker() { return assignedWorker; }
        public void setAssignedWorker(String workerId) { this.assignedWorker = workerId; }
        public Future<?> getFuture() { return future; }
        public void setFuture(Future<?> future) { this.future = future; }
    }
    
    public DistributedTaskScheduler(int corePoolSize) {
        this.executor = Executors.newFixedThreadPool(corePoolSize);
        this.workerNodes = new CopyOnWriteArrayList<>();
        this.tasks = new ConcurrentHashMap<>();
        this.taskIdCounter = new AtomicInteger(0);
        this.lock = new ReentrantLock();
        this.healthCheckScheduler = Executors.newScheduledThreadPool(1);
        
        // Start health check
        startHealthCheck();
    }
    
    private void startHealthCheck() {
        healthCheckScheduler.scheduleAtFixedRate(() -> {
            checkWorkerHealth();
            reassignFailedTasks();
        }, 30, 30, TimeUnit.SECONDS);
    }
    
    private void checkWorkerHealth() {
        long currentTime = System.currentTimeMillis();
        long threshold = currentTime - 60000; // 1 minute timeout
        
        for (WorkerNode worker : workerNodes) {
            if (worker.getLastHeartbeat() < threshold) {
                worker.setHealthy(false);
                System.err.println(""Worker "" + worker.getId() + "" marked as unhealthy"");
            }
        }
    }
    
    private void reassignFailedTasks() {
        lock.lock();
        try {
            for (ScheduledTask task : tasks.values()) {
                if (task.getStatus() == ScheduledTask.TaskStatus.RUNNING) {
                    WorkerNode assignedWorker = findWorkerById(task.getAssignedWorker());
                    if (assignedWorker == null || !assignedWorker.isHealthy()) {
                        // Task is running on failed worker, reschedule
                        rescheduleTask(task);
                    }
                }
            }
        } finally {
            lock.unlock();
        }
    }
    
    private void rescheduleTask(ScheduledTask task) {
        task.setStatus(ScheduledTask.TaskStatus.PENDING);
        task.setAssignedWorker(null);
        if (task.getFuture() != null) {
            task.getFuture().cancel(false);
        }
        
        scheduleTask(task);
    }
    
    private WorkerNode findWorkerById(String workerId) {
        if (workerId == null) return null;
        
        for (WorkerNode worker : workerNodes) {
            if (worker.getId().equals(workerId)) {
                return worker;
            }
        }
        return null;
    }
    
    public void registerWorker(WorkerNode worker) {
        workerNodes.add(worker);
        System.out.println(""Registered worker: "" + worker.getId());
    }
    
    public void unregisterWorker(String workerId) {
        workerNodes.removeIf(worker -> worker.getId().equals(workerId));
        
        // Reassign tasks from removed worker
        reassignFailedTasks();
    }
    
    public String scheduleTask(Runnable task, long initialDelay, 
                             long period, TimeUnit unit) {
        String taskId = ""task-"" + taskIdCounter.incrementAndGet();
        ScheduledTask scheduledTask = new ScheduledTask(taskId, task, 
                                                       initialDelay, period, unit);
        
        tasks.put(taskId, scheduledTask);
        scheduleTask(scheduledTask);
        
        return taskId;
    }
    
    private void scheduleTask(ScheduledTask scheduledTask) {
        WorkerNode worker = selectWorker();
        if (worker == null)",1,DEEPSEEK,Design a task scheduler that can distribute tasks across multiple worker nodes and handle failures.,JAVA
,"import java.util.Scanner;
class MinMaxInArray
{
int getMax(int[]inputArray)
{
int maxValue=inputArray[0];
for(int i=1;i<inputArray.length;i++)
{
if(inputArray[i]>maxValue)
{
maxValue=inputArray[i];
}
}
return maxValue;
}
int getMin(int[]inputArray)
{
int minValue=inputArray[0];
for(int i=1;i<inputArray.length;i++)
{
if(inputArray[i]<minValue)
{
minValue=inputArray[i];
}
}

return minValue;
}
}
public class ExArrayDifference
{
public static void main(String[] args)
{
int n;
Scanner sc = new Scanner(System.in);
System.out.print(""Enter number of elements you wants to enter :"" );
n=sc.nextInt();
int arr[]=new int[n];
for(int i=0;i<arr.length;i++)
{
System.out.print(""Enter [""+(i+1)+""] element :"" );
arr[i]=sc.nextInt();
}
MinMaxInArray mm=new MinMaxInArray();
System.out.println(""Maximum value is :"" +mm.getMax(arr));
System.out.println(""Minimum value is :"" +mm.getMin(arr));
int Difference=mm.getMax(arr)-mm.getMin(arr);
System.out.print(""Difference between Minnimum and Maximum in array is : ""
+Difference );
}
}",0,IPSGWALIOR.ORG,NA,JAVA
,"import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

public class SlidingWindowRateLimiter {
    private final int maxRequests;
    private final long windowMillis;
    private final ConcurrentHashMap<String, Window> userWindows;
    
    private static class Window {
        final ConcurrentLinkedQueue<Long> timestamps;
        final AtomicInteger currentRequests;
        
        Window() {
            this.timestamps = new ConcurrentLinkedQueue<>();
            this.currentRequests = new AtomicInteger(0);
        }
    }
    
    public SlidingWindowRateLimiter(int maxRequests, long windowDuration, TimeUnit timeUnit) {
        this.maxRequests = maxRequests;
        this.windowMillis = timeUnit.toMillis(windowDuration);
        this.userWindows = new ConcurrentHashMap<>();
    }
    
    public boolean allowRequest(String userId) {
        Window window = userWindows.computeIfAbsent(userId, k -> new Window());
        long currentTime = System.currentTimeMillis();
        long cutoffTime = currentTime - windowMillis;
        
        // Clean old timestamps
        while (!window.timestamps.isEmpty() && 
               window.timestamps.peek() < cutoffTime) {
            window.timestamps.poll();
            window.currentRequests.decrementAndGet();
        }
        
        // Check if under limit
        if (window.currentRequests.get() >= maxRequests) {
            return false;
        }
        
        // Add new request
        window.timestamps.offer(currentTime);
        window.currentRequests.incrementAndGet();
        return true;
    }
    
    public void reset(String userId) {
        userWindows.remove(userId);
    }
}",1,DEEPSEEK,Create a rate limiter that allows N requests per minute with sliding window algorithm.,JAVA
,"class NoOfOccurenceOfCharacters
{
 static final int MAX_CHAR = 256;
 static void getOccuringChar(String str)
 {
 int count[] = new int[MAX_CHAR];
 int len = str.length();
 for (int i = 0; i < len; i++)
 count[str.charAt(i)]++;
 char ch[] = new char[str.length()];
 for (int i = 0; i < len; i++) {
 ch[i] = str.charAt(i);
 int find = 0;
 for (int j = 0; j <= i; j++) {
 if (str.charAt(i) == ch[j])
 find++;
 }
 if (find == 1)
 System.out.println(""Number of Occurrence of "" +

 str.charAt(i) + "" is:"" + count[str.charAt(i)]);
 }
 }
 public static void main(String[] args)
 {
 Scanner sc = new Scanner(System.in);
 String str = ""geeksforgeeks"";
 getOccuringChar(str);
 }
}",0,IPSGWALIOR.ORG,NA,JAVA
,"import java.time.Duration;
import java.util.concurrent.Callable;
import java.util.concurrent.ThreadLocalRandom;
import java.util.function.Predicate;

public class RetryExecutor {
    private final int maxAttempts;
    private final Duration initialDelay;
    private final Duration maxDelay;
    private final double backoffMultiplier;
    private final Predicate<Exception> retryPredicate;
    
    private RetryExecutor(Builder builder) {
        this.maxAttempts = builder.maxAttempts;
        this.initialDelay = builder.initialDelay;
        this.maxDelay = builder.maxDelay;
        this.backoffMultiplier = builder.backoffMultiplier;
        this.retryPredicate = builder.retryPredicate;
    }
    
    public <T> T execute(Callable<T> task) throws Exception {
        Exception lastException = null;
        Duration currentDelay = initialDelay;
        
        for (int attempt = 1; attempt <= maxAttempts; attempt++) {
            try {
                return task.call();
            } catch (Exception e) {
                lastException = e;
                
                if (attempt == maxAttempts || !shouldRetry(e)) {
                    throw e;
                }
                
                if (attempt < maxAttempts) {
                    sleepWithJitter(currentDelay);
                    currentDelay = calculateNextDelay(currentDelay);
                }
            }
        }
        
        throw lastException;
    }
    
    private boolean shouldRetry(Exception e) {
        return retryPredicate == null || retryPredicate.test(e);
    }
    
    private void sleepWithJitter(Duration delay) {
        try {
            long jitter = ThreadLocalRandom.current().nextLong(
                (long) (delay.toMillis() * 0.1)
            );
            Thread.sleep(delay.toMillis() + jitter);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            throw new RuntimeException(""Retry interrupted"", e);
        }
    }
    
    private Duration calculateNextDelay(Duration currentDelay) {
        long nextDelayMillis = (long) (currentDelay.toMillis() * backoffMultiplier);
        if (nextDelayMillis > maxDelay.toMillis()) {
            nextDelayMillis = maxDelay.toMillis();
        }
        return Duration.ofMillis(nextDelayMillis);
    }
    
    public static class Builder {
        private int maxAttempts = 3;
        private Duration initialDelay = Duration.ofMillis(100);
        private Duration maxDelay = Duration.ofSeconds(30);
        private double backoffMultiplier = 2.0;
        private Predicate<Exception> retryPredicate;
        
        public Builder maxAttempts(int maxAttempts) {
            this.maxAttempts = maxAttempts;
            return this;
        }
        
        public Builder initialDelay(Duration initialDelay) {
            this.initialDelay = initialDelay;
            return this;
        }
        
        public Builder maxDelay(Duration maxDelay) {
            this.maxDelay = maxDelay;
            return this;
        }
        
        public Builder backoffMultiplier(double backoffMultiplier) {
            this.backoffMultiplier = backoffMultiplier;
            return this;
        }
        
        public Builder retryOn(Predicate<Exception> retryPredicate) {
            this.retryPredicate = retryPredicate;
            return this;
        }
        
        public RetryExecutor build() {
            return new RetryExecutor(this);
        }
    }
}",1,DEEPSEEK,Create a retry mechanism that handles transient failures with exponential backoff.,JAVA
,"// Define the Cat class
public class Cat {
    // Private instance variables
    private String name;
    private int age;
    // Default constructor
    public Cat() {
        // Initialize name to ""Unknown""
        this.name = ""Unknown"";
        // Initialize age to 0
        this.age = 0;
    }
    // Getter for name
    public String getName() {
        return name;
    }
    // Getter for age
    public int getAge() {
        return age;
    }
    // Main method to test the Cat class
    public static void main(String[] args) {
        // Create a new Cat object using the default constructor
        Cat myCat = new Cat();
        // Use the getter methods to access private variables
        System.out.println(""Cat's Name: "" + myCat.getName());

        System.out.println(""Cat's Age: "" + myCat.getAge());
    }
}
",0,WE3RESOURCE,NA,JAVA
,"import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

public class DatabaseConnectionPool {
    private final BlockingQueue<PooledConnection> availableConnections;
    private final AtomicInteger activeConnections = new AtomicInteger(0);
    private final int maxPoolSize;
    private final String url;
    private final String username;
    private final String password;
    private volatile boolean isClosed = false;
    
    public DatabaseConnectionPool(String url, String username, 
                                 String password, int maxPoolSize) {
        this.url = url;
        this.username = username;
        this.password = password;
        this.maxPoolSize = maxPoolSize;
        this.availableConnections = new LinkedBlockingQueue<>(maxPoolSize);
        initializePool();
    }
    
    private void initializePool() {
        for (int i = 0; i < maxPoolSize / 2; i++) {
            try {
                availableConnections.offer(createConnection());
            } catch (SQLException e) {
                throw new RuntimeException(""Failed to initialize connection pool"", e);
            }
        }
    }
    
    private PooledConnection createConnection() throws SQLException {
        Connection connection = DriverManager.getConnection(url, username, password);
        return new PooledConnection(connection, this);
    }
    
    public Connection getConnection() throws SQLException {
        return getConnection(30, TimeUnit.SECONDS);
    }
    
    public Connection getConnection(long timeout, TimeUnit unit) throws SQLException {
        if (isClosed) {
            throw new SQLException(""Connection pool is closed"");
        }
        
        try {
            // Try to get existing connection
            PooledConnection pooledConn = availableConnections.poll(timeout, unit);
            if (pooledConn != null) {
                if (!pooledConn.getConnection().isValid(2)) {
                    closeQuietly(pooledConn.getConnection());
                    pooledConn = createConnection();
                }
                activeConnections.incrementAndGet();
                return pooledConn;
            }
            
            // Create new connection if pool not full
            if (activeConnections.get() < maxPoolSize) {
                PooledConnection newConn = createConnection();
                activeConnections.incrementAndGet();
                return newConn;
            }
            
            throw new SQLException(""Connection pool exhausted"");
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            throw new SQLException(""Interrupted while waiting for connection"");
        }
    }
    
    void returnConnection(PooledConnection connection) {
        if (isClosed) {
            closeQuietly(connection.getConnection());
            return;
        }
        
        try {
            if (connection.getConnection().isClosed() || 
                !connection.getConnection().isValid(2)) {
                closeQuietly(connection.getConnection());
                availableConnections.offer(createConnection());
            } else {
                availableConnections.offer(connection);
            }
        } catch (SQLException e) {
            // Connection is invalid, create new one
            closeQuietly(connection.getConnection());
            try {
                availableConnections.offer(createConnection());
            } catch (SQLException ex) {
                // Log error but don't throw

            }

        } finally {

            activeConnections.decrementAndGet();

        }

    }

    

    public void close() {

        isClosed = true;

        availableConnections.forEach(conn -> 

            closeQuietly(conn.getConnection())

        );

        availableConnections.clear();

    }

    

    public int getActiveConnections() {

        return activeConnections.get();

    }

    

    public int getIdleConnections() {

        return availableConnections.size();

    }

    

    private void closeQuietly(Connection connection) {

        try {

            if (connection != null && !connection.isClosed()) {

                connection.close();

            }

        } catch (SQLException e) {

            // Ignore

        }

    }

    

    private class PooledConnection extends ConnectionWrapper {

        private final DatabaseConnectionPool pool;

        

        PooledConnection(Connection connection, DatabaseConnectionPool pool) {

            super(connection);

            this.pool = pool;

        }

        

        @Override

        public void close() throws SQLException {

            pool.returnConnection(this);

        }

    }

    

    private abstract class ConnectionWrapper implements Connection {

        protected final Connection delegate;

        

        ConnectionWrapper(Connection delegate) {

            this.delegate = delegate;

        }

        

        // Delegate all Connection methods to the wrapped connection

        @Override

        public Statement createStatement() throws SQLException {

            return delegate.createStatement();

        }

        

        // ... implement all other Connection methods similarly

        

        @Override

        public boolean isWrapperFor(Class<?> iface) throws SQLException {

            return iface.isInstance(delegate) || delegate.isWrapperFor(iface);

        }

        

        @SuppressWarnings(""unchecked"")

        @Override

        public <T> T unwrap(Class<T> iface) throws SQLException {

            if (iface.isInstance(delegate)) {

                return (T) delegate;

            }

            return delegate.unwrap(iface);

        }

    }

}",1,DEEPSEEK,Create a generic connection pool for managing database connections.,JAVA

,"// Define the Dog class

public class Dog {

    // Private instance variables

    private String name;

    private String color;



    // Parameterized constructor

    public Dog(String name, String color) {

        // Initialize name with the provided parameter

        this.name = name;

        // Initialize color with the provided parameter

        this.color = color;

    }



    // Main method to test the Dog class

    public static void main(String[] args) {

        // Create a new Dog object using the parameterized constructor

        Dog myDog = new Dog(""Bailey"", ""Black"");

        // Print the values of the instance variables

        System.out.println(""Dog's Name: "" + myDog.name);
        System.out.println(""Dog's Color: "" + myDog.color);

    }

}
",0,WE3RESOURCE,NA,JAVA

,"import java.time.Instant;

import java.util.*;

import java.util.concurrent.ConcurrentHashMap;

import java.util.concurrent.atomic.AtomicLong;

import java.util.stream.Collectors;



public class EventStore {

    private final ConcurrentHashMap<String, List<Event>> streams;

    private final ConcurrentHashMap<String, AtomicLong> streamVersions;

    

    public EventStore() {

        this.streams = new ConcurrentHashMap<>();

        this.streamVersions = new ConcurrentHashMap<>();

    }

    

    public static class Event {

        private final String eventId;

        private final String streamId;

        private final String eventType;

        private final Map<String, Object> data;

        private final Map<String, Object> metadata;

        private final Instant timestamp;

        private final long version;

        

        public Event(String streamId, String eventType, 

                    Map<String, Object> data, long version) {

            this.eventId = UUID.randomUUID().toString();

            this.streamId = streamId;

            this.eventType = eventType;

            this.data = Collections.unmodifiableMap(new HashMap<>(data));

            this.metadata = new HashMap<>();

            this.timestamp = Instant.now();

            this.version = version;

        }

        

        // Getters

        public String getEventId() { return eventId; }

        public String getStreamId() { return streamId; }

        public String getEventType() { return eventType; }

        public Map<String, Object> getData() { return data; }

        public Map<String, Object> getMetadata() { return metadata; }

        public Instant getTimestamp() { return timestamp; }

        public long getVersion() { return version; }

        

        public void addMetadata(String key, Object value) {

            metadata.put(key, value);

        }

    }

    

    public AppendResult appendToStream(String streamId, List<Event> events, 

                                      long expectedVersion) {

        if (events == null || events.isEmpty()) {

            throw new IllegalArgumentException(""Events cannot be empty"");

        }

        

        streams.compute(streamId, (key, existingEvents) -> {

            long currentVersion = streamVersions

                .computeIfAbsent(streamId, k -> new AtomicLong(0))

                .get();

            

            // Optimistic concurrency check

            if (expectedVersion != -1 && currentVersion != expectedVersion) {

                throw new ConcurrencyException(

                    String.format(""Expected version %d but was %d"", 

                                 expectedVersion, currentVersion)

                );

            }

            

            List<Event> streamEvents = existingEvents != null ? 

                new ArrayList<>(existingEvents) : new ArrayList<>();

            

            // Assign versions to events

            for (int i = 0; i < events.size(); i++) {

                Event event = events.get(i);

                Event versionedEvent = new Event(

                    streamId,

                    event.eventType,

                    event.data,

                    currentVersion + i + 1

                );

                event.metadata.forEach(versionedEvent::addMetadata);

                streamEvents.add(versionedEvent);

            }

            

            // Update version

            streamVersions.get(streamId).addAndGet(events.size());

            

            return Collections.unmodifiableList(streamEvents);

        });

        

        return new AppendResult(streamId, 

            streamVersions.get(streamId).get(), 

            events.size()

        );

    }

    

    public List<Event> readStream(String streamId) {

        List<Event> events = streams.get(streamId);

        return events != null ? new ArrayList<>(events) : new ArrayList<>();

    }

    

    public List<Event> readStream(String streamId, long fromVersion) {

        List<Event> events = streams.get(streamId);

        if (events == null) {

            return new ArrayList<>();

        }

        

        return events.stream()

            .filter(e -> e.getVersion() >= fromVersion)

            .collect(Collectors.toList());

    }

    

    public List<Event> readAllEvents() {

        return streams.values().stream()

            .flatMap(List::stream)

            .sorted(Comparator.comparing(Event::getTimestamp)

                    .thenComparing(Event::getVersion))

            .collect(Collectors.toList());

    }

    

    public long getStreamVersion(String streamId) {

        AtomicLong version = streamVersions.get(streamId);

        return version != null ? version.get() : 0;

    }

    

    public void subscribe(EventSubscriber subscriber) {

        // Implementation for event subscription

    }

    

    public static class AppendResult {

        private final String streamId;

        private final long newVersion;

        private final int eventsAppended;

        

        AppendResult(String streamId, long newVersion, int eventsAppended) {

            this.streamId = streamId;

            this.newVersion = newVersion;

            this.eventsAppended = eventsAppended;

        }

        

        public String getStreamId() { return streamId; }

        public long getNewVersion() { return newVersion; }

        public int getEventsAppended() { return eventsAppended; }

    }

    

    public interface EventSubscriber {

        void handle(Event event);

    }

    

    public static class ConcurrencyException extends RuntimeException {

        public ConcurrencyException(String message) {

            super(message);

        }

    }

}",1,DEEPSEEK,Create an event store for CQRS pattern with optimistic concurrency control.,JAVA

,"// Define the Book class

public class Book {

    // Private instance variables

    private String title;

    private String author;

    private double price;



    // Default constructor

    public Book() {

        // Initialize title to ""Unknown""

        this.title = ""Unknown"";

        // Initialize author to ""Unknown""

        this.author = ""Unknown"";

        // Initialize price to 0.0

        this.price = 0.0;

    }



    // Parameterized constructor (title, author)

    public Book(String title, String author) {

        // Initialize title with the provided parameter

        this.title = title;

        // Initialize author with the provided parameter

        this.author = author;

        // Initialize price to 0.0

        this.price = 0.0;

    }



    // Parameterized constructor (title, author, price)

    public Book(String title, String author, double price) {

        // Initialize title with the provided parameter

        this.title = title;

        // Initialize author with the provided parameter

        this.author = author;

        // Initialize price with the provided parameter

        this.price = price;

    }



    // Main method to test the Book class

    public static void main(String[] args) {

        // Create a new Book object using the default constructor

        Book book1 = new Book();

        // Print the values of the instance variables for book1

        System.out.println(""Book1 Title: "" + book1.title);

        System.out.println(""Book1 Author: "" + book1.author);

        System.out.println(""Book1 Price: "" + book1.price);



        // Create a new Book object using the parameterized constructor (title, author)

        Book book2 = new Book(""Amatka"", ""Karin Tidbeck"");

        // Print the values of the instance variables for book2

        System.out.println(""Book2 Title: "" + book2.title);

        System.out.println(""Book2 Author: "" + book2.author);

        System.out.println(""Book2 Price: "" + book2.price);



        // Create a new Book object using the parameterized constructor (title, author, price)

        Book book3 = new Book(""Altered Carbon"", ""Richard K. Morgan"", 18.99);

        // Print the values of the instance variables for book3

        System.out.println(""Book3 Title: "" + book3.title);

        System.out.println(""Book3 Author: "" + book3.author);

        System.out.println(""Book3 Price: "" + book3.price);

    }

}
",0,WE3RESOURCE,NA,JAVA

,"import java.time.Instant;

import java.util.concurrent.atomic.AtomicLong;



public class SnowflakeIdGenerator {

    private static final long EPOCH = 1609459200000L; // 2021-01-01

    private static final long WORKER_ID_BITS = 5L;

    private static final long DATACENTER_ID_BITS = 5L;

    private static final long SEQUENCE_BITS = 12L;

    

    private static final long MAX_WORKER_ID = (1L << WORKER_ID_BITS) - 1;

    private static final long MAX_DATACENTER_ID = (1L << DATACENTER_ID_BITS) - 1;

    private static final long MAX_SEQUENCE = (1L << SEQUENCE_BITS) - 1;

    

    private static final long WORKER_ID_SHIFT = SEQUENCE_BITS;

    private static final long DATACENTER_ID_SHIFT = SEQUENCE_BITS + WORKER_ID_BITS;

    private static final long TIMESTAMP_SHIFT = SEQUENCE_BITS + WORKER_ID_BITS + DATACENTER_ID_BITS;

    

    private final long workerId;

    private final long datacenterId;

    private final AtomicLong sequence = new AtomicLong(0);

    private volatile long lastTimestamp = -1L;

    

    public SnowflakeIdGenerator(long workerId, long datacenterId) {

        if (workerId > MAX_WORKER_ID || workerId < 0) {

            throw new IllegalArgumentException(

                String.format(""Worker ID must be between 0 and %d"", MAX_WORKER_ID)

            );

        }

        if (datacenterId > MAX_DATACENTER_ID || datacenterId < 0) {

            throw new IllegalArgumentException(

                String.format(""Datacenter ID must be between 0 and %d"", MAX_DATACENTER_ID)

            );

        }

        

        this.workerId = workerId;

        this.datacenterId = datacenterId;

    }

    

    public synchronized long nextId() {

        long timestamp = currentTimestamp();

        

        if (timestamp < lastTimestamp) {

            throw new IllegalStateException(

                String.format(""Clock moved backwards. Refusing to generate ID for %d milliseconds"",

                            lastTimestamp - timestamp)

            );

        }

        

        if (timestamp == lastTimestamp) {

            long currentSequence = (sequence.incrementAndGet() & MAX_SEQUENCE);

            if (currentSequence == 0) {

                // Sequence overflow, wait for next millisecond

                timestamp = waitNextMillis(lastTimestamp);

            }

        } else {

            sequence.set(0);

        }

        

        lastTimestamp = timestamp;

        

        return ((timestamp - EPOCH) << TIMESTAMP_SHIFT) |

               (datacenterId << DATACENTER_ID_SHIFT) |

               (workerId << WORKER_ID_SHIFT) |

               sequence.get();

    }

    

    public String nextIdAsString() {

        return Long.toString(nextId());

    }

    

    public Instant getTimestampFromId(long id) {

        long timestamp = (id >> TIMESTAMP_SHIFT) + EPOCH;

        return Instant.ofEpochMilli(timestamp);

    }

    

    public long getWorkerIdFromId(long id) {

        return (id >> WORKER_ID_SHIFT) & MAX_WORKER_ID;

    }

    

    public long getDatacenterIdFromId(long id) {

        return (id >> DATACENTER_ID_SHIFT) & MAX_DATACENTER_ID;

    }

    

    public long getSequenceFromId(long id) {

        return id & MAX_SEQUENCE;

    }

    

    private long waitNextMillis(long lastTimestamp) {

        long timestamp = currentTimestamp();

        while (timestamp <= lastTimestamp) {

            timestamp = currentTimestamp();

        }

        return timestamp;

    }

    

    private long currentTimestamp() {

        return System.currentTimeMillis();

    }

    

    public static class IdMetadata {

        private final long id;

        private final Instant timestamp;

        private final long workerId;

        private final long datacenterId;

        private final long sequence;

        

        public IdMetadata(long id) {

            this.id = id;

            SnowflakeIdGenerator generator = new SnowflakeIdGenerator(0, 0);

            this.timestamp = generator.getTimestampFromId(id);

            this.workerId = generator.getWorkerIdFromId(id);

            this.datacenterId = generator.getDatacenterIdFromId(id);

            this.sequence = generator.getSequenceFromId(id);

        }

        

        // Getters

        public long getId() { return id; }

        public Instant getTimestamp() { return timestamp; }

        public long getWorkerId() { return workerId; }

        public long getDatacenterId() { return datacenterId; }

        public long getSequence() { return sequence; }

        

        @Override

        public String toString() {

            return String.format(

                ""ID: %d, Timestamp: %s, Worker: %d, Datacenter: %d, Sequence: %d"",

                id, timestamp, workerId, datacenterId, sequence

            );

        }

    }

}",1,DEEPSEEK,Create a distributed unique ID generator similar to Twitter's Snowflake.,JAVA
,"// Define the Student class
public class Student {
    // Private instance variables
    private int studentId;
    private String studentName;
    private String grade;

    // Default constructor
    public Student() {
        // Call the parameterized constructor with default values
        this(0, ""Unknown"", ""None"");
    }

    // Parameterized constructor
    public Student(int studentId, String studentName, String grade) {
        // Initialize studentId with the provided parameter
        this.studentId = studentId;
        // Initialize studentName with the provided parameter
        this.studentName = studentName;
        // Initialize grade with the provided parameter
        this.grade = grade;
    }

    // Main method to test the Student class
    public static void main(String[] args) {
        // Create a new Student object using the default constructor
        Student student1 = new Student();
        // Print the values of the instance variables for student1
        System.out.println(""Student1 ID: "" + student1.studentId);
        System.out.println(""Student1 Name: "" + student1.studentName);
        System.out.println(""Student1 Grade: "" + student1.grade);

        // Create a new Student object using the parameterized constructor
        Student student2 = new Student(101, ""Cullen"", ""A"");
        // Print the values of the instance variables for student2
        System.out.println(""Student2 ID: "" + student2.studentId);
        System.out.println(""Student2 Name: "" + student2.studentName);
        System.out.println(""Student2 Grade: "" + student2.grade);
    }
}
",0,WE3RESOURCE,NA,JAVA
,"import java.util.Comparator;
import java.util.PriorityQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class PriorityMessageQueue<T> {
    private final PriorityQueue<Message<T>> queue;
    private final ReentrantLock lock;
    private final Condition notEmpty;
    private final Condition notFull;
    private final int maxCapacity;
    private volatile boolean shutdown;
    
    public enum Priority {
        HIGH, MEDIUM, LOW
    }
    
    private static class Message<T> {
        final T payload;
        final Priority priority;
        final long timestamp;
        final String messageId;
        int deliveryAttempts;
        
        Message(T payload, Priority priority) {
            this.payload = payload;
            this.priority = priority;
            this.timestamp = System.currentTimeMillis();
            this.messageId = java.util.UUID.randomUUID().toString();
            this.deliveryAttempts = 0;
        }
        
        long getPriorityScore() {
            long priorityMultiplier;
            switch (priority) {
                case HIGH: priorityMultiplier = 1000; break;
                case MEDIUM: priorityMultiplier = 100; break;
                default: priorityMultiplier = 1;
            }
            return timestamp / priorityMultiplier;
        }
    }
    
    private static class MessageComparator<T> implements Comparator<Message<T>> {
        @Override
        public int compare(Message<T> m1, Message<T> m2) {
            return Long.compare(m1.getPriorityScore(), m2.getPriorityScore());
        }
    }
    
    public PriorityMessageQueue(int maxCapacity) {
        this.maxCapacity = maxCapacity;
        this.queue = new PriorityQueue<>(new MessageComparator<>());
        this.lock = new ReentrantLock();
        this.notEmpty = lock.newCondition();
        this.notFull = lock.newCondition();
        this.shutdown = false;
    }
    
    public boolean enqueue(T payload, Priority priority) {
        return enqueue(payload, priority, -1, TimeUnit.MILLISECONDS);
    }
    
    public boolean enqueue(T payload, Priority priority, 
                          long timeout, TimeUnit unit) {
        if (payload == null) throw new NullPointerException();
        if (shutdown) throw new IllegalStateException(""Queue is shutdown"");
        
        lock.lock();
        try {
            long nanos = unit.toNanos(timeout);
            
            while (queue.size() >= maxCapacity && !shutdown) {
                if (nanos <= 0) {
                    return false;
                }
                nanos = notFull.awaitNanos(nanos);
            }
            
            if (shutdown) return false;
            
            Message<T> message = new Message<>(payload, priority);
            queue.offer(message);
            notEmpty.signal();
            return true;
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            return false;
        } finally {
            lock.unlock();
        }
    }
    
    public Message<T> dequeue() throws InterruptedException {
        return dequeue(-1, TimeUnit.MILLISECONDS);
    }
    
    public Message<T> dequeue(long timeout, TimeUnit unit) 
            throws InterruptedException {
        lock.lock();
        try {
            long nanos = unit.toNanos(timeout);
            
            while (queue.isEmpty() && !shutdown) {
                if (nanos <= 0) {
                    return null;
                }
                nanos = notEmpty.awaitNanos(nanos);
            }
            
            if (queue.isEmpty() && shutdown) {
                return null;
            }
            
            Message<T> message = queue.poll();
            notFull.signal();
            
            if (message != null) {
                message.deliveryAttempts++;
            }
            
            return message;
        } finally {
            lock.unlock();
        }
    }
    
    public void acknowledge(String messageId) {
        // In a real implementation, this would track delivery status
        // For simplicity, we just remove from queue
        lock.lock();
        try {
            queue.removeIf(msg -> msg.messageId.equals(messageId));
            notFull.signal();
        } finally {
            lock.unlock();
        }
    }
    
    public void requeue(Message<T> message) {
        lock.lock();
        try {
            if (message.deliveryAttempts < 3) {
                queue.offer(message);
                notEmpty.signal();
            } else {
                // Move to dead letter queue or log
                System.err.println(""Message "" + message.messageId + 
                                 "" exceeded max delivery attempts"");
            }
        } finally {
            lock.unlock();
        }
    }
    
    public int size() {
        lock.lock();
        try {
            return queue.size();
        } finally {
            lock.unlock();
        }
    }
    
    public boolean isEmpty() {
        lock.lock();
        try {
            return queue.isEmpty();
        } finally {
            lock.unlock();
        }
    }
    
    public void shutdown() {
        lock.lock();
        try {
            shutdown = true;
            notEmpty.signalAll();
            notFull.signalAll();
        } finally {
            lock.unlock();
        }
    }
    
    public void clear() {
        lock.lock();
        try {
            queue.clear();
            notFull.signalAll();
        } finally {
            lock.unlock();
        }
    }
}",1,DEEPSEEK,Create a thread-safe message queue with priority levels and delivery guarantees.,JAVA
,"// Define the Rectangle class
public class Rectangle {
    // Private instance variables
    private double length;
    private double width;

    // Parameterized constructor
    public Rectangle(double length, double width) {
        // Initialize length with the provided parameter
        this.length = length;
        // Initialize width with the provided parameter
        this.width = width;
    }

    // Copy constructor
    public Rectangle(Rectangle rectangle) {
        // Initialize length with the length of the provided rectangle object
        this.length = rectangle.length;
        // Initialize width with the width of the provided rectangle object
        this.width = rectangle.width;
    }

    // Main method to test the Rectangle class
    public static void main(String[] args) {
        // Create a new Rectangle object using the parameterized constructor
        Rectangle rect1 = new Rectangle(12.5, 4.5);
        // Print the values of the instance variables for rect1
        System.out.println(""Rectangle 1 Length: "" + rect1.length);
        System.out.println(""Rectangle 1 Width: "" + rect1.width);

        // Create a new Rectangle object using the copy constructor
        Rectangle rect2 = new Rectangle(rect1);
        // Print the values of the instance variables for rect2
        System.out.println(""Rectangle 2 Length: "" + rect2.length);
        System.out.println(""Rectangle 2 Width: "" + rect2.width);
    }
}
",0,WE3RESOURCE,NA,JAVA
,"import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.params.SetParams;

import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class RedisDistributedLock implements Lock {
    private final JedisPool jedisPool;
    private final String lockKey;
    private final String lockValue;
    private final long leaseTimeMillis;
    private final long waitTimeMillis;
    private final ScheduledExecutorService renewalExecutor;
    
    private final ThreadLocal<Boolean> locked = ThreadLocal.withInitial(() -> false);
    private final ThreadLocal<Integer> lockCount = ThreadLocal.withInitial(() -> 0);
    private final ConcurrentHashMap<String, LockRenewalTask> renewalTasks;
    
    private final ReentrantLock internalLock = new ReentrantLock();
    private final Condition lockReleased = internalLock.newCondition();
    
    public RedisDistributedLock(JedisPool jedisPool, String lockKey, 
                               long leaseTimeMillis, long waitTimeMillis) {
        this.jedisPool = jedisPool;
        this.lockKey = lockKey;
        this.lockValue = UUID.randomUUID().toString();
        this.leaseTimeMillis = leaseTimeMillis;
        this.waitTimeMillis = waitTimeMillis;
        this.renewalExecutor = Executors.newSingleThreadScheduledExecutor();
        this.renewalTasks = new ConcurrentHashMap<>();
    }
    
    @Override
    public void lock() {
        try {
            if (!tryLock(waitTimeMillis, TimeUnit.MILLISECONDS)) {
                throw new RuntimeException(""Failed to acquire lock within timeout"");
            }
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            throw new RuntimeException(""Interrupted while acquiring lock"", e);
        }
    }
    
    @Override
    public void lockInterruptibly() throws InterruptedException {
        if (!tryLock(waitTimeMillis, TimeUnit.MILLISECONDS)) {
            throw new RuntimeException(""Failed to acquire lock within timeout"");
        }
    }
    
    @Override
    public boolean tryLock() {
        return tryAcquireLock();
    }
    
    @Override
    public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
        long waitUntil = System.currentTimeMillis() + unit.toMillis(time);
        
        while (System.currentTimeMillis() < waitUntil) {
            if (tryAcquireLock()) {
                return true;
            }
            
            synchronized (this) {
                long remaining = waitUntil - System.currentTimeMillis();
                if (remaining > 0) {
                    wait(100); // Wait and retry
                }
            }
            
            if (Thread.interrupted()) {
                throw new InterruptedException();
            }
        }
        
        return false;
    }
    
    private boolean tryAcquireLock() {
        if (locked.get()) {
            // Reentrant lock
            lockCount.set(lockCount.get() + 1);
            return true;
        }
        
        try (Jedis jedis = jedisPool.getResource()) {
            SetParams params = SetParams.setParams()
                .nx()
                .px(leaseTimeMillis);
            
            String result = jedis.set(lockKey, lockValue, params);
            
            if (""OK"".equals(result)) {
                locked.set(true);
                lockCount.set(1);
                startLockRenewal();
                return true;
            }
        }
        
        return false;
    }
    
    private void startLockRenewal() {
        LockRenewalTask task = new LockRenewalTask(lockKey, lockValue, leaseTimeMillis);
        renewalTasks.put(lockValue, task);
        
        // Schedule renewal at half the lease time
        renewalExecutor.scheduleAtFixedRate(
            task,
            leaseTimeMillis / 2,
            leaseTimeMillis / 2,
            TimeUnit.MILLISECONDS
        );
    }
    
    @Override
    public void unlock() {
        if (!locked.get()) {
            throw new IllegalMonitorStateException(""Lock not held by current thread"");
        }
        
        int count = lockCount.get() - 1;
        lockCount.set(count);
        
        if (count == 0) {
            locked.set(false);
            releaseLock();
        }
    }
    
    private void releaseLock() {
        LockRenewalTask task = renewalTasks.remove(lockValue);
        if (task != null) {
            task.cancel();
        }
        
        try (Jedis jedis = jedisPool.getResource()) {
            // Use Lua script for atomic release
            String luaScript = 
                ""if redis.call('get', KEYS[1]) == ARGV[1] then "" +
                ""    return redis.call('del', KEYS[1]) "" +
                ""else "" +
                ""    return 0 "" +
                ""end"";
            
            jedis.eval(luaScript, 1, lockKey, lockValue);
        }
        
        internalLock.lock();
        try {
            lockReleased.signalAll();
        } finally {
            internalLock.unlock();
        }
    }
    
    @Override
    public Condition newCondition() {
        throw new UnsupportedOperationException(""Conditions not supported"");
    }
    
    private static class LockRenewalTask implements Runnable {
        private final String lockKey;
        private final String lockValue;
        private final long leaseTimeMillis;
        private volatile boolean cancelled;
        
        LockRenewalTask(String lockKey, String lockValue, long leaseTimeMillis) {
            this.lockKey = lockKey;
            this.lockValue = lockValue;
            this.leaseTimeMillis = leaseTimeMillis;
            this.cancelled = false;
        }
        
        @Override
        public void run() {
            if (cancelled) {
                return;
            }
            
            try (Jedis jedis = new Jedis(""localhost"")) {
                String luaScript = 
                    ""if redis.call('get', KEYS[1]) == ARGV[1] then "" +
                    ""    return redis.call('pexpire', KEYS[1], ARGV[2]) "" +
                    ""else "" +
                    ""    return 0 "" +
                    ""end"";
                
                Long result = (Long) jedis.eval(
                    luaScript, 1, lockKey, lockValue, 
                    String.valueOf(leaseTimeMillis)
                );
                
                if (result == 0) {
                    // Lock was released or stolen
                    cancel();
                }
            } catch (Exception e) {
                // Log error but don't throw

                System.err.println(""Failed to renew lock: "" + e.getMessage());

            }

        }

        

        void cancel() {

            this.cancelled = true;

        }

    }

    

    public void shutdown() {

        renewalExecutor.shutdown();

        try {

            if (!renewalExecutor.awaitTermination(5, TimeUnit.SECONDS)) {

                renewalExecutor.shutdownNow();

            }

        } catch (InterruptedException e) {

            renewalExecutor.shutdownNow();

            Thread.currentThread().interrupt();

        }

    }

}",1,DEEPSEEK,Create a distributed lock using Redis with lease time and automatic renewal.,JAVA

,"// Define the Account class

public class Account {

    // Private instance variables

    private String accountNumber;

    private double balance;



    // Parameterized constructor with validation

    public Account(String accountNumber, double balance) {

        // Validate accountNumber

        if (accountNumber == null || accountNumber.isEmpty()) {

            // Print error message if accountNumber is null or empty

            System.err.println(""Error: Account number cannot be null or empty."");

            return;

        }

        // Validate balance

        if (balance < 0) {

            // Print error message if balance is negative

            System.err.println(""Error: Balance cannot be negative."");

            return;

        }

        // Initialize accountNumber with the provided parameter

        this.accountNumber = accountNumber;

        // Initialize balance with the provided parameter

        this.balance = balance;

    }



    // Main method to test the Account class

    public static void main(String[] args) {

        // Test with valid data

        Account account1 = new Account(""12340009"", 1000.00);

        System.out.println(""Account 1 Number: "" + account1.accountNumber);

        System.out.println(""Account 1 Balance: "" + account1.balance);



        // Test with invalid accountNumber

        Account account2 = new Account("""", 400.00);



        // Test with invalid balance

        Account account3 = new Account(""1230000873"", -200.00);

    }

}
",0,WE3RESOURCE,NA,JAVA

,"import java.util.Map;

import java.util.concurrent.ConcurrentHashMap;

import java.util.concurrent.TimeUnit;

import java.util.concurrent.atomic.AtomicInteger;

import java.util.concurrent.atomic.AtomicLong;



public class ApiRateLimiter {

    private final Map<String, RateLimiter> limiters;

    private final RateLimitConfig config;

    

    public ApiRateLimiter(RateLimitConfig config) {

        this.limiters = new ConcurrentHashMap<>();

        this.config = config;

    }

    

    public boolean allowRequest(String clientId, String endpoint) {

        String key = clientId + "":"" + endpoint;

        RateLimiter limiter = limiters.computeIfAbsent(key, 

            k -> createRateLimiter(endpoint)

        );

        

        return limiter.tryAcquire();

    }

    

    private Rate",1,DEEPSEEK,Create an API gateway rate limiter with multiple rate limiting strategies.,JAVA

,"// Define the Car class

public class Car {

    // Private instance variables

    private String make;

    private String model;

    private int year;



    // Parameterized constructor with default values

    public Car(String make, String model, int year) {

        // Initialize make with the provided parameter or a default value

        this.make = (make == null || make.isEmpty()) ? ""Unknown Make"" : make;

        // Initialize model with the provided parameter or a default value

        this.model = (model == null || model.isEmpty()) ? ""Unknown Model"" : model;

        // Initialize year with the provided parameter or a default value

        this.year = (year <= 0) ? 2000 : year;

    }



    // Main method to test the Car class

    public static void main(String[] args) {

        // Create a new Car object with valid data

        Car car1 = new Car(""Toyota"", ""Corolla"", 2021);

        // Print the values of the instance variables for car1

        System.out.println(""Car 1 Make: "" + car1.make);

        System.out.println(""Car 1 Model: "" + car1.model);

        System.out.println(""Car 1 Year: "" + car1.year);



        // Create a new Car object with some invalid data

        Car car2 = new Car("""", """", -1);

        // Print the values of the instance variables for car2

        System.out.println(""Car 2 Make: "" + car2.make);

        System.out.println(""Car 2 Model: "" + car2.model);

        System.out.println(""Car 2 Year: "" + car2.year);

    }

}
",0,WERESOURCE,NA,JAVA

,"static String reverseWords(String s){

    String[] w=s.trim().split(""\\s+"");

    StringBuilder b=new StringBuilder();

    for(int i=w.length-1;i>=0;i--) b.append(w[i]).append("" "");

    return b.toString().trim();

}
",1,GPT,"Given a sentence, reverse the order of words without reversing characters.",JAVA

,"// Define the Point class

public class Point {

    // Private instance variables

    private int x;

    private int y;



    // Constructor that takes int parameters

    public Point(int x, int y) {

        // Initialize instance variables

        this.x = x;

        this.y = y;

    }



    // Constructor that takes double parameters

    public Point(double x, double y) {

        // Initialize instance variables by casting double to int

        this.x = (int) x;

        this.y = (int) y;

    }



    // Method to print the values of x and y

    public void printPoint() {

        System.out.println(""Point (x, y): ("" + x + "", "" + y + "")"");

    }



    // Main method to test the Point class

    public static void main(String[] args) {

        // Create a Point object using the int constructor

        Point point1 = new Point(4, 5);

        // Print the values of point1

        point1.printPoint();



        // Create a Point object using the double constructor

        Point point2 = new Point(4.5, 5.5);

        // Print the values of point2

        point2.printPoint();

    }

}
",0,WE3RESOURCE,NA,JAVA

,"static int subarraySum(int[] a,int k){

    Map<Integer,Integer> m=new HashMap<>();

    m.put(0,1); int sum=0,res=0;

    for(int x:a){

        sum+=x;

        res+=m.getOrDefault(sum-k,0);

        m.put(sum,m.getOrDefault(sum,0)+1);

    }

    return res;

}
",1,GPT,"Given an integer array nums and integer k, return the number of continuous subarrays whose sum equals k.",JAVA

,"// Define the Classroom class

public class Classroom {

    // Private instance variables

    private String className;

    private String[] students;



    // Parameterized constructor that initializes className and students

    public Classroom(String className, String[] students) {

        // Initialize instance variables with provided parameters

        this.className = className;

        this.students = students;

    }



    // Method to print the values of className and students

    public void printClassroom() {

        System.out.println(""Class Name: "" + className);

        System.out.print(""Students: "");

        for (String student : students) {

            System.out.print(student + "" "");

        }

        System.out.println();

    }



    // Main method to test the Classroom class

    public static void main(String[] args) {

        // Create an array of student names

        String[] studentArray = {""Andrine"", ""Ruslan"", ""Martin""};

        // Create a Classroom object using the parameterized constructor

        Classroom classroom = new Classroom(""Science 101"", studentArray);

        // Print the values of the instance variables

        classroom.printClassroom();

    }

}
",0,WE3RESOURCE,NA,JAVA

,"static int longestSeq(int[] a){

    Set<Integer> s=new HashSet<>();

    for(int x:a) s.add(x);

    int best=0;

    for(int x:s)

        if(!s.contains(x-1)){

            int y=x;

            while(s.contains(y)) y++;

            best=Math.max(best,y-x);

        }

    return best;

}
",1,GPT,Find the length of the longest sequence of consecutive integers in an unsorted array,JAVA

,"// Define the Singleton class

public class Singleton {

    // Private static variable to hold the single instance

    private static Singleton singleInstance = null;



    // Private constructor to prevent instantiation

    private Singleton() {

        // Print a message indicating the creation of the instance

        System.out.println(""Singleton instance created."");

    }



    // Public static method to get the single instance of the class

    public static Singleton getInstance() {

        // If the single instance is null, create a new instance

        if (singleInstance == null) {

            singleInstance = new Singleton();

        }

        // Return the single instance

        return singleInstance;

    }



    // Main method to test the Singleton class

    public static void main(String[] args) {

        // Get the single instance of Singleton

        Singleton instance1 = Singleton.getInstance();

        // Try to get another instance of Singleton

        Singleton instance2 = Singleton.getInstance();



        // Check if both instances are the same

        if (instance1 == instance2) {

            System.out.println(""Both instances are the same."");

        } else {

            System.out.println(""Instances are different."");

        }

    }

}
",0,WE3RESOURCE,NA,JAVA

,"static int[] prod(int[] a){

    int n=a.length; int[] r=new int[n];

    r[0]=1;

    for(int i=1;i<n;i++) r[i]=r[i-1]*a[i-1];

    int p=1;

    for(int i=n-1;i>=0;i--){ r[i]*=p; p*=a[i]; }

    return r;

}
",1,GPT,Return an array where each element is product of all other elements without using division.,JAVA

,"//IncrementThread.java

public class IncrementThread extends Thread {

  private Counter counter;

  private int incrementsPerThread;

  public IncrementThread(Counter counter, int incrementsPerThread) {

    this.counter = counter;

    this.incrementsPerThread = incrementsPerThread;

  }

  @Override

  public void run() {

    for (int i = 0; i < incrementsPerThread; i++) {

      counter.increment();

    }

  }

}
",0,WE3RESOURCE,NA,JAVA

,"static List<Integer> anagrams(String s,String p){

    int[] c=new int[26];

    for(char x:p.toCharArray()) c[x-'a']++;

    int l=0,r=0,cnt=p.length();

    List<Integer> res=new ArrayList<>();

    while(r<s.length()){

        if(c[s.charAt(r++)-'a']-- >0) cnt--;

        if(cnt==0) res.add(l);

        if(r-l==p.length() && c[s.charAt(l++)-'a']++ >=0) cnt++;

    }

    return res;

}
",1,GPT,Find all start indices of p's anagrams in s.,JAVA
,"// ProducerConsumer.java
import java.util.LinkedList;
import java.util.Queue;

public class ProducerConsumer {
  private static final int BUFFER_SIZE = 5;
  private static final Queue < Integer > buffer = new LinkedList < > ();

  public static void main(String[] args) {
    Thread producerThread = new Thread(new Producer());
    Thread consumerThread = new Thread(new Consumer());

    producerThread.start();
    consumerThread.start();
  }

  static class Producer implements Runnable {
    public void run() {
      int value = 0;
      while (true) {
        synchronized(buffer) {
          // Wait if the buffer is full
          while (buffer.size() == BUFFER_SIZE) {
            try {
              buffer.wait();
            } catch (InterruptedException e) {
              e.printStackTrace();
            }
          }

          System.out.println(""Producer produced: "" + value);
          buffer.add(value++);

          // Notify the consumer that an item is produced
          buffer.notify();

          try {
            Thread.sleep(1000);
          } catch (InterruptedException e) {
            e.printStackTrace();
          }
        }
      }
    }
  }

  static class Consumer implements Runnable {
    public void run() {
      while (true) {
        synchronized(buffer) {
          // Wait if the buffer is empty
          while (buffer.isEmpty()) {
            try {
              buffer.wait();
            } catch (InterruptedException e) {
              e.printStackTrace();
            }
          }

          int value = buffer.poll();
          System.out.println(""Consumer consumed: "" + value);

          // Notify the producer that an item is consumed
          buffer.notify();

          try {
            Thread.sleep(1000);
          } catch (InterruptedException e) {
            e.printStackTrace();
          }
        }
      }
    }
  }
}
",0,WE3RESOURCE,NA,JAVA
,"static int[][] kClose(int[][] p,int k){
    PriorityQueue<int[]> q=new PriorityQueue<>(
        (a,b)->b[0]*b[0]+b[1]*b[1]-a[0]*a[0]-a[1]*a[1]);
    for(int[] x:p){ q.add(x); if(q.size()>k) q.poll(); }
    return q.toArray(new int[k][2]);
}
",1,GPT,"WRITE A JAVA PROGRAM WHERE THE Given points in 2D, return k closest points to origin.",JAVA
,"// SharedResourceExercise.java
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class SharedResourceExercise {
  private static final int NUM_THREADS = 3;
  private static final int NUM_ITERATIONS = 5;

  public static void main(String[] args) {
    Lock lock = new ReentrantLock();
    SharedResource sharedResource = new SharedResource();

    Thread[] threads = new Thread[NUM_THREADS];
    for (int i = 0; i < NUM_THREADS; i++) {
      threads[i] = new Thread(new Worker(lock, sharedResource));
      threads[i].start();
    }

    try {
      for (Thread thread: threads) {
        thread.join();
      }
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
  }

  static class Worker implements Runnable {
    private Lock lock;
    private SharedResource sharedResource;

    public Worker(Lock lock, SharedResource sharedResource) {
      this.lock = lock;
      this.sharedResource = sharedResource;
    }

    public void run() {
      for (int i = 0; i < NUM_ITERATIONS; i++) {
        lock.lock();
        try {
          sharedResource.doWork();
        } finally {
          lock.unlock();
        }
      }
    }
  }

  static class SharedResource {
    public void doWork() {
      String threadName = Thread.currentThread().getName();
      System.out.println(""Thread-> "" + threadName + "" is performing work."");
      // Perform work on the shared resource
    }
  }
}
",0,WE3RESOURCE,NA,JAVA
,"static String decode(String s){
    Stack<Integer> n=new Stack<>();
    Stack<String> st=new Stack<>();
    String cur=""""; int k=0;
    for(char c:s.toCharArray()){
        if(Character.isDigit(c)) k=k*10+c-'0';
        else if(c=='['){ n.push(k); st.push(cur); k=0; cur=""""; }
        else if(c==']'){ cur=st.pop()+cur.repeat(n.pop()); }
        else cur+=c;
    }
    return cur;
}
",1,GPT,"write a java program toDecode strings like ""3[a2[c]]""""accaccacc"".",JAVA
,"//SemaphoreExercise.java
import java.util.concurrent.Semaphore;

public class SemaphoreExercise {
  private static final int NUM_THREADS = 5;
  private static final int NUM_PERMITS = 2;

  public static void main(String[] args) {
    Semaphore semaphore = new Semaphore(NUM_PERMITS);

    Thread[] threads = new Thread[NUM_THREADS];
    for (int i = 0; i < NUM_THREADS; i++) {
      threads[i] = new Thread(new Worker(semaphore));
      threads[i].start();
    }

    try {
      for (Thread thread: threads) {
        thread.join();
      }
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
  }

  static class Worker implements Runnable {
    private Semaphore semaphore;

    public Worker(Semaphore semaphore) {
      this.semaphore = semaphore;
    }

    public void run() {
      try {
        semaphore.acquire();

        // Perform work that requires the semaphore
        System.out.println(""Thread "" + Thread.currentThread().getName() + "" acquired the semaphore."");
        Thread.sleep(2000); // Simulating work
        System.out.println(""Thread "" + Thread.currentThread().getName() + "" released the semaphore."");

        semaphore.release();
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }
  }
}
",0,WE3RESOURCE,NA,JAVA
,"static boolean canFinish(int n,int[][] p){
    List<Integer>[] g=new ArrayList[n];
    for(int i=0;i<n;i++) g[i]=new ArrayList<>();
    int[] in=new int[n];
    for(int[] e:p){ g[e[1]].add(e[0]); in[e[0]]++; }
    Queue<Integer> q=new LinkedList<>();
    for(int i=0;i<n;i++) if(in[i]==0) q.add(i);
    int c=0;
    while(!q.isEmpty()){
        int x=q.poll(); c++;
        for(int y:g[x]) if(--in[y]==0) q.add(y);
    }
    return c==n;
}
",1,GPT,"Given prerequisites, determine if all courses can be finished. WRITE A CYCLE DETECTION GRAPH BASED JAVA PROGRAM FOR THIS CONDITION.",JAVA
,"import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

public class CyclicBarrierExercise {
  private static final int NUM_THREADS = 3;
  private static final CyclicBarrier barrier = new CyclicBarrier(NUM_THREADS, new BarrierAction());

  public static void main(String[] args) {
    Thread[] threads = new Thread[NUM_THREADS];
    for (int i = 0; i < NUM_THREADS; i++) {
      threads[i] = new Thread(new Worker());
      threads[i].start();
    }

    try {
      for (Thread thread: threads) {
        thread.join();
      }
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
  }

  static class Worker implements Runnable {
    public void run() {
      try {
        System.out.println(""Thread "" + Thread.currentThread().getName() + "" is waiting at the barrier."");
        barrier.await();

        // Perform work after reaching the barrier

        System.out.println(""Thread "" + Thread.currentThread().getName() + "" has crossed the barrier and continued execution."");
      } catch (InterruptedException | BrokenBarrierException e) {
        e.printStackTrace();
      }
    }
  }

  static class BarrierAction implements Runnable {
    public void run() {
      System.out.println(""Barrier reached! All threads have arrived at the barrier."");
    }
  }
}
",0,WE3RESOURCE,NA,JAVA
,"static void ser(Node r,StringBuilder b){
    if(r==null){b.append(""#,"");return;}
    b.append(r.val).append("","");
    ser(r.left,b); ser(r.right,b);
}
static Node des(Queue<String> q){
    String s=q.poll();
    if(s.equals(""#"")) return null;
    Node n=new Node(Integer.parseInt(s));
    n.left=des(q); n.right=des(q);
    return n;
}
",1,GPT,Convert binary tree to string and restore it.,JAVA
,"import java.util.concurrent.CountDownLatch;

public class CountDownLatchExercise {
  private static final int NUM_THREADS = 3;
  private static final CountDownLatch startLatch = new CountDownLatch(1);
  private static final CountDownLatch finishLatch = new CountDownLatch(NUM_THREADS);

  public static void main(String[] args) {
    Thread[] threads = new Thread[NUM_THREADS];
    for (int i = 0; i < NUM_THREADS; i++) {
      threads[i] = new Thread(new Worker());
      threads[i].start();
    }

    // Allow threads to start simultaneously
    startLatch.countDown();

    try {
      finishLatch.await();
    } catch (InterruptedException e) {
      e.printStackTrace();
    }

    System.out.println(""All threads have finished their work."");
  }

  static class Worker implements Runnable {
    public void run() {
      try {
        startLatch.await();

        // Perform work

        System.out.println(""Thread "" + Thread.currentThread().getName() + "" has finished its work."");
      } catch (InterruptedException e) {
        e.printStackTrace();
      } finally {
        finishLatch.countDown();
      }
    }
  }
}
",0,WE3RESOURCE,NA,JAVA
,"static String minWin(String s,String t){
    int[] c=new int[128]; for(char x:t.toCharArray()) c[x]++;
    int l=0,start=0,min=Integer.MAX_VALUE,need=t.length();
    for(int r=0;r<s.length();r++){
        if(c[s.charAt(r)]-- >0) need--;
        while(need==0){
            if(r-l+1<min){min=r-l+1;start=l;}
            if(c[s.charAt(l++)]++==0) need++;
        }
    }
    return min==Integer.MAX_VALUE?"""":s.substring(start,start+min);
}
",1,GPT,write a java program to Find smallest substring in s containing all chars of t.,JAVA
,"import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class ReadWriteLockExercise {
  private static final int NUM_READERS = 3;
  private static final int NUM_WRITERS = 2;

  public static void main(String[] args) {
    ReadWriteLock lock = new ReentrantReadWriteLock();
    SharedResource sharedResource = new SharedResource();

    // Create and start the reader threads
    for (int i = 0; i < NUM_READERS; i++) {
      Thread readerThread = new Thread(new Reader(lock, sharedResource));
      readerThread.start();
    }

    // Create and start the writer threads
    for (int i = 0; i < NUM_WRITERS; i++) {
      Thread writerThread = new Thread(new Writer(lock, sharedResource));
      writerThread.start();
    }
  }

  static class Reader implements Runnable {
    private ReadWriteLock lock;
    private SharedResource sharedResource;

    public Reader(ReadWriteLock lock, SharedResource sharedResource) {
      this.lock = lock;
      this.sharedResource = sharedResource;
    }

    public void run() {
      while (true) {
        lock.readLock().lock();

        // Read from the shared resource
        System.out.println(""Reader "" + Thread.currentThread().getName() + "" reads: "" + sharedResource.read());

        lock.readLock().unlock();

        // Delay between consecutive reads
        try {
          Thread.sleep(1000);
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
      }
    }
  }

  static class Writer implements Runnable {
    private ReadWriteLock lock;
    private SharedResource sharedResource;
    private int counter = 0;

    public Writer(ReadWriteLock lock, SharedResource sharedResource) {
      this.lock = lock;
      this.sharedResource = sharedResource;
    }

    public void run() {
      while (true) {
        lock.writeLock().lock();

        // Write to the shared resource
        sharedResource.write(""Writer "" + Thread.currentThread().getName() + "" writes: "" + counter++);

        lock.writeLock().unlock();

        // Delay between consecutive writes
        try {
          Thread.sleep(2000);
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
      }
    }
  }

  static class SharedResource {
    private String data;

    public String read() {
      return data;
    }

    public void write(String data) {
      this.data = data;
    }
  }
}
",0,WE3RESOURCE,NA,JAVA
,"static int ladder(String b,String e,List<String> w){
    Set<String> s=new HashSet<>(w); Queue<String> q=new LinkedList<>();
    q.add(b); int lvl=1;
    while(!q.isEmpty()){
        for(int i=q.size();i>0;i--){
            String x=q.poll();
            if(x.equals(e)) return lvl;
            for(int j=0;j<x.length();j++)
                for(char c='a';c<='z';c++){
                    char[] a=x.toCharArray(); a[j]=c;
                    String y=new String(a);
                    if(s.remove(y)) q.add(y);
                }
        } lvl++;
    } return 0;
}
",1,GPT,write a java program to Transform begin word to end word by changing one letter at a time.,JAVA
,"import java.util.concurrent.ConcurrentHashMap;

public class ConcurrentHashMapExercise {
  public static void main(String[] args) {
    ConcurrentHashMap < String, Integer > map = new ConcurrentHashMap < > ();

    // Create and start the writer threads
    Thread writerThread1 = new Thread(new Writer(map, ""Thread-1"", 1));
    Thread writerThread2 = new Thread(new Writer(map, ""Thread-2"", 2));
    writerThread1.start();
    writerThread2.start();

    // Create and start the reader threads
    Thread readerThread1 = new Thread(new Reader(map, ""Thread-1""));
    Thread readerThread2 = new Thread(new Reader(map, ""Thread-2""));
    readerThread1.start();
    readerThread2.start();
  }

  static class Writer implements Runnable {
    private ConcurrentHashMap < String, Integer > map;
    private String threadName;
    private int value;

    public Writer(ConcurrentHashMap < String, Integer > map, String threadName, int value) {
      this.map = map;
      this.threadName = threadName;
      this.value = value;
    }

    public void run() {
      for (int i = 0; i < 5; i++) {
        map.put(threadName, value);
        try {
          Thread.sleep(1000);
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
      }
    }
  }

  static class Reader implements Runnable {
    private ConcurrentHashMap < String, Integer > map;
    private String threadName;

    public Reader(ConcurrentHashMap < String, Integer > map, String threadName) {
      this.map = map;
      this.threadName = threadName;
    }

    public void run() {
      for (int i = 0; i < 5; i++) {
        Integer value = map.get(threadName);
        System.out.println(""Thread "" + threadName + "" read value: "" + value);
        try {
          Thread.sleep(1000);
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
      }
    }
  }
}
",0,WE3RESOURCE,NA,JAVA
,"static int maxRect(int[] h){
    Stack<Integer> s=new Stack<>(); int max=0;
    for(int i=0;i<=h.length;i++){
        int cur=i==h.length?0:h[i];
        while(!s.isEmpty()&&cur<h[s.peek()]){
            int ht=h[s.pop()];
            int w=s.isEmpty()?i:i-s.peek()-1;
            max=Math.max(max,ht*w);
        } s.push(i);
    } return max;
}
",1,GPT,write a program to Find largest rectangle area in histogram.,JAVA
,"import java.util.concurrent.ConcurrentLinkedQueue;

public class ConcurrentQueueExercise {
  public static void main(String[] args) {
    ConcurrentLinkedQueue < String > queue = new ConcurrentLinkedQueue < > ();

    // Create and start the producer threads
    Thread producerThread1 = new Thread(new Producer(queue, ""Producer-1""));
    Thread producerThread2 = new Thread(new Producer(queue, ""Producer-2""));
    producerThread1.start();
    producerThread2.start();

    // Create and start the consumer threads
    Thread consumerThread1 = new Thread(new Consumer(queue, ""Consumer-1""));
    Thread consumerThread2 = new Thread(new Consumer(queue, ""Consumer-2""));
    consumerThread1.start();
    consumerThread2.start();
  }

  static class Producer implements Runnable {
    private ConcurrentLinkedQueue < String > queue;
    private String producerName;
    private int counter;

    public Producer(ConcurrentLinkedQueue < String > queue, String producerName) {
      this.queue = queue;
      this.producerName = producerName;
      this.counter = 0;
    }

    public void run() {
      while (true) {
        String item = producerName + ""-Item-"" + counter++;
        queue.offer(item);
        System.out.println(""Produced: "" + item);

        try {
          Thread.sleep(1000);
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
      }
    }
  }

  static class Consumer implements Runnable {
    private ConcurrentLinkedQueue < String > queue;
    private String consumerName;

    public Consumer(ConcurrentLinkedQueue < String > queue, String consumerName) {
      this.queue = queue;
      this.consumerName = consumerName;
    }

    public void run() {
      while (true) {
        String item = queue.poll();
        if (item != null) {
          System.out.println(consumerName + "" consumed: "" + item);
        }

        try {
          Thread.sleep(1500);
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
      }
    }
  }
}
",0,WE3RESOURCE,NA,JAVA
,"static int max=Integer.MIN_VALUE;
static int path(Node n){
    if(n==null) return 0;
    int l=Math.max(0,path(n.left)), r=Math.max(0,path(n.right));
    max=Math.max(max,l+r+n.val);
    return Math.max(l,r)+n.val;
}
",1,GPT,write a java program to Find max sum of any path in tree.,JAVA
,"import java.util.concurrent.Phaser;

public class PhaserExercise {

  public static void main(String[] args) {
    // Create a Phaser with 4 registered parties
    Phaser phaser = new Phaser(4);

    // Create and start three worker threads
    Thread thread1 = new Thread(new Worker(phaser, ""Thread 1""));
    Thread thread2 = new Thread(new Worker(phaser, ""Thread 2""));
    Thread thread3 = new Thread(new Worker(phaser, ""Thread 3""));
    Thread thread4 = new Thread(new Worker(phaser, ""Thread 4""));
    thread1.start();
    thread2.start();
    thread3.start();
    thread4.start();

    // Wait for all threads to complete
    phaser.awaitAdvance(phaser.getPhase());

    System.out.println(""All threads have completed their tasks."");
  }

  static class Worker implements Runnable {
    private final Phaser phaser;
    private final String name;

    public Worker(Phaser phaser, String name) {
      this.phaser = phaser;
      this.name = name;
    }

    @Override
    public void run() {
      System.out.println(name + "" starting phase 1"");
      phaser.arriveAndAwaitAdvance(); // Wait for all threads to reach this point

      // Perform phase 1 tasks
      System.out.println(name + "" performing phase 1 tasks"");

      // Wait for all threads to complete phase 1
      phaser.arriveAndAwaitAdvance();

      System.out.println(name + "" starting phase 2"");
      phaser.arriveAndAwaitAdvance(); // Wait for all threads to reach this point

      // Perform phase 2 tasks
      System.out.println(name + "" performing phase 2 tasks"");

      // Wait for all threads to complete phase 2
      phaser.arriveAndAwaitAdvance();

      System.out.println(name + "" completed all phases"");
      phaser.arriveAndDeregister(); // Deregister from the Phaser
    }
  }
}
",0,WE3RESOURCE,NA,JAVA
,"static String alien(String[] w){
    Map<Character,Set<Character>> g=new HashMap<>();
    Map<Character,Integer> in=new HashMap<>();
    for(String s:w) for(char c:s.toCharArray()){g.putIfAbsent(c,new HashSet<>());in.putIfAbsent(c,0);}
    for(int i=0;i<w.length-1;i++)
        for(int j=0;j<Math.min(w[i].length(),w[i+1].length());j++)
            if(w[i].charAt(j)!=w[i+1].charAt(j)){
                if(g.get(w[i].charAt(j)).add(w[i+1].charAt(j)))
                    in.put(w[i+1].charAt(j),in.get(w[i+1].charAt(j))+1);
                break;
            }
    Queue<Character> q=new LinkedList<>();
    for(char c:in.keySet()) if(in.get(c)==0) q.add(c);
    StringBuilder r=new StringBuilder();
    while(!q.isEmpty()){
        char c=q.poll(); r.append(c);
        for(char n:g.get(c)) if(in.put(n,in.get(n)-1)==1) q.add(n);
    }
    return r.toString();
}
",1,GPT,give me an java code to Find character order from sorted alien words.,JAVA
,"import java.util.concurrent.Exchanger;

public class ExchangerExercise {

  public static void main(String[] args) {
    Exchanger < String > exchanger = new Exchanger < > ();

    // Create and start two worker threads
    Thread thread1 = new Thread(new Worker(exchanger, ""Data from Thread 1""));
    Thread thread2 = new Thread(new Worker(exchanger, ""Data from Thread 2""));
    thread1.start();
    thread2.start();
  }

  static class Worker implements Runnable {
    private final Exchanger < String > exchanger;
    private final String data;

    public Worker(Exchanger < String > exchanger, String data) {
      this.exchanger = exchanger;
      this.data = data;
    }

    @Override
    public void run() {
      try {
        System.out.println(Thread.currentThread().getName() + "" sending data: "" + data);
        String receivedData = exchanger.exchange(data); // Exchange data with the other thread

        System.out.println(Thread.currentThread().getName() + "" received data: "" + receivedData);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }
  }
}
",0,WE3RESOURCE,NA,JAVA
,"static boolean dfs(char[][] b,int i,int j,String w,int k){
    if(k==w.length()) return true;
    if(i<0||j<0||i==b.length||j==b[0].length||b[i][j]!=w.charAt(k)) return false;
    char t=b[i][j]; b[i][j]='#';
    boolean r=dfs(b,i+1,j,w,k+1)||dfs(b,i-1,j,w,k+1)||dfs(b,i,j+1,w,k+1)||dfs(b,i,j-1,w,k+1);
    b[i][j]=t; return r;
}
",1,GPT,give me an efficient java code to Find if word exists in grid using DFS + Trie.,JAVA
,"import java.util.concurrent.*;

public class CallableFutureExercise {

  public static void main(String[] args) {
    // Create a thread pool with a single worker thread
    ExecutorService executor = Executors.newSingleThreadExecutor();

    // Submit a Callable task to the executor
    Future < String > future = executor.submit(new Task());

    // Perform other operations while the task is executing

    try {
      // Wait for the task to complete and get the result
      String result = future.get();

      System.out.println(""Task result: "" + result);
    } catch (InterruptedException | ExecutionException e) {
      e.printStackTrace();
    }

    // Shutdown the executor
    executor.shutdown();
  }

  static class Task implements Callable < String > {
    @Override
    public String call() throws Exception {
      // Perform the task and return the result
      Thread.sleep(2000); // Simulate some time-consuming operation
      return ""Task completed!"";
    }
  }
}
",0,WE3RESOURCE,NA,JAVA
,"static int[] redundant(int[][] e){
    int[] p=new int[1001];
    for(int i=1;i<p.length;i++) p[i]=i;
    for(int[] x:e){
        int a=f(p,x[0]),b=f(p,x[1]);
        if(a==b) return x;
        p[a]=b;
    } return null;
}
static int f(int[] p,int x){ return p[x]==x?x:(p[x]=f(p,p[x])); }
",1,GPT,write a java code to Find extra edge forming cycle.,JAVA
,"import java.util.Date;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class ScheduledExecutorExercise {

  public static void main(String[] args) {
    ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);

    // Schedule a task to run after a delay of 2 seconds
    executor.schedule(new Task(), 2, TimeUnit.SECONDS);

    // Schedule a task to run after a delay of 3 seconds and repeat every 5 seconds
    executor.scheduleAtFixedRate(new Task(), 3, 5, TimeUnit.SECONDS);

    // Wait for scheduled tasks to complete
    try {
      Thread.sleep(15000);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }

    // Shutdown the executor
    executor.shutdown();
  }

  static class Task implements Runnable {
    @Override
    public void run() {
      System.out.println(""Task executed at: "" + new Date());
    }
  }
}
",0,WE3RESOURCE,NA,JAVA
,"static boolean match(String s,String p){
    boolean[][] d=new boolean[s.length()+1][p.length()+1];
    d[0][0]=true;
    for(int j=2;j<=p.length();j++)
        if(p.charAt(j-1)=='*') d[0][j]=d[0][j-2];
    for(int i=1;i<=s.length();i++)
        for(int j=1;j<=p.length();j++)
            if(p.charAt(j-1)=='*')
                d[i][j]=d[i][j-2]||(d[i-1][j]&&(p.charAt(j-2)=='.'||p.charAt(j-2)==s.charAt(i-1)));
            else
                d[i][j]=d[i-1][j-1]&&(p.charAt(j-1)=='.'||p.charAt(j-1)==s.charAt(i-1));
    return d[s.length()][p.length()];
}
",1,GPT,write a java program to Implement regex matcher with . and *. ,JAVA
,"import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveTask;

public class ForkJoinPoolExercise {

  public static void main(String[] args) {
    int[] array = {
      1,
      2,
      3,
      4,
      5,
      6,
      7,
      8,
      9,
      10
    };

    ForkJoinPool forkJoinPool = new ForkJoinPool();

    int sum = forkJoinPool.invoke(new SumTask(array, 0, array.length));

    System.out.println(""Sum: "" + sum);
  }

  static class SumTask extends RecursiveTask < Integer > {
    private final int[] array;
    private final int start;
    private final int end;

    public SumTask(int[] array, int start, int end) {
      this.array = array;
      this.start = start;
      this.end = end;
    }

    @Override
    protected Integer compute() {
      if (end - start <= 2) {
        int sum = 0;
        for (int i = start; i < end; i++) {
          sum += array[i];
        }
        return sum;
      } else {
        int mid = start + (end - start) / 2;

        SumTask leftTask = new SumTask(array, start, mid);
        SumTask rightTask = new SumTask(array, mid, end);

        invokeAll(leftTask, rightTask);

        return leftTask.join() + rightTask.join();
      }
    }
  }
}
",0,WE3RESOURCE,NA,JAVA
,"static int decodeWays(String s){
    if(s.charAt(0)=='0') return 0;
    int a=1,b=1;
    for(int i=1;i<s.length();i++){
        int c=0;
        if(s.charAt(i)!='0') c=b;
        int x=Integer.parseInt(s.substring(i-1,i+1));
        if(x>=10&&x<=26) c+=a;
        a=b; b=c;
    } return b;
}
",1,GPT,"You are given a string s containing only digits ('0''9') that represents an encoded message where:

'A'""1""

'B'""2""

...

'Z'""26""

Write a java function to determine how many different ways the string can be decoded into letters.",JAVA
,"import java.util.concurrent.locks.StampedLock;

public class StampedLockExercise {

    public static void main(String[] args) {
        SharedResource sharedResource = new SharedResource();

        // Start multiple reader threads
        for (int i = 0; i < 5; i++) {
            new Thread(() -> {
                int value = sharedResource.getValue();
                System.out.println(""Reader thread: "" + Thread.currentThread().getName() + "", value: "" + value);
            }).start();
        }

        // Start a writer thread
        new Thread(() -> {
            sharedResource.setValue(42);
            System.out.println(""Writer thread: "" + Thread.currentThread().getName() + "" set value to 42"");
        }).start();
    }

    static class SharedResource {
        private int value;
        private final StampedLock lock = new StampedLock();

        public int getValue() {
            long stamp = lock.tryOptimisticRead(); // Optimistically acquire a read lock

            int currentValue = value;

            if (!lock.validate(stamp)) { // Check for concurrent write
                stamp = lock.readLock(); // Upgrade to a read lock
                try {
                    currentValue = value;
                } finally {
                    lock.unlockRead(stamp); // Release the read lock
                }
            }

            return currentValue;
        }

        public void setValue(int value) {
            long stamp = lock.writeLock(); // Acquire a write lock

            try {
                this.value = value;
            } finally {
                lock.unlockWrite(stamp); // Release the write lock
            }
        }
    }
}
",0,WE3RESOURCE,NA,JAVA
,"static int dfs(int[][] m,int i,int j,int[][] d){
    if(d[i][j]>0) return d[i][j];
    int r=1;
    for(int[] x:new int[][]{{1,0},{-1,0},{0,1},{0,-1}}){
        int a=i+x[0],b=j+x[1];
        if(a>=0&&b>=0&&a<m.length&&b<m[0].length&&m[a][b]>m[i][j])
            r=Math.max(r,1+dfs(m,a,b,d));
    }
    return d[i][j]=r;
}
",1,GPT,"You are given an m x n integer matrix matrix.
From any cell, you can move up, down, left, or right to another cell only if the next cell has a strictly larger value.

Write a java function that returns the length of the longest strictly increasing path in the matrix.",JAVA
,"public int romanToInt(String s) {
         int ans = 0, num = 0;
        for (int i = s.length()-1; i >= 0; i--) {
            switch(s.charAt(i)) {
                case 'I': num = 1; break;
                case 'V': num = 5; break;
                case 'X': num = 10; break;
                case 'L': num = 50; break;
                case 'C': num = 100; break;
                case 'D': num = 500; break;
                case 'M': num = 1000; break;
            }
            if (4 * num < ans) ans -= num;
            else ans += num;
        }
        return ans;
    }",0,leetcode,NA,JAVA
,"// 1. Binary Search (AI-generated for sorted array lookup)
public class BinarySearch {
    public static int search(int[] arr, int target) {
        int left = 0, right = arr.length - 1;
        while (left <= right) {
            int mid = left + (right - left) / 2;
            if (arr[mid] == target) return mid;
            if (arr[mid] < target) left = mid + 1;
            else right = mid - 1;
        }
        return -1;
    }
}
",1,PERPLEXITY,Write a Java method for binary search on a sorted integer array that returns the index or -1 if not found,JAVA
,"class Solution {
    public String intToRoman(int num) {
        String Roman = """";
        int[][] storeIntRoman = {{1000, ""M""}, {900, ""CM""}, {500, ""D""}, {400, ""CD""}, {100, ""C""}, {90, ""XC""}, {50, ""L""}, {40, ""XL""}, {10, ""X""}, {9, ""IX""}, {5, ""V""}, {4, ""IV""}, {1, ""I""}};
        for (int i = 0; i < storeIntRoman.length; i++) {
            while (num >= storeIntRoman[i][0]) {
                Roman += storeIntRoman[i][1];
                num -= storeIntRoman[i][0];
            }
        }
        return Roman;
    }
}",0,leetcode,NA,JAVA
,"public class BubbleSort {
    public static void sort(int[] arr) {
        int n = arr.length;
        for (int i = 0; i < n - 1; i++) {
            for (int j = 0; j < n - i - 1; j++) {
                if (arr[j] > arr[j + 1]) {
                    int temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                }
            }
        }
    }
}
",1,PERPLEXITY,Create a Java class with a static method to sort an integer array using bubble sort in-place.,JAVA
,"class Solution {
    private Map<Character, String> digitToLetters = new HashMap<>();
    private List<String> resultList = new ArrayList<>();

    public List<String> letterCombinations(String digits) {
        if (digits == null || digits.length() == 0) {
            return resultList;
        }

        digitToLetters.put('2', ""abc"");
        digitToLetters.put('3', ""def"");
        digitToLetters.put('4', ""ghi"");
        digitToLetters.put('5', ""jkl"");
        digitToLetters.put('6', ""mno"");
        digitToLetters.put('7', ""pqrs"");
        digitToLetters.put('8', ""tuv"");
        digitToLetters.put('9', ""wxyz"");

        generateCombinations(digits, 0, new StringBuilder());

        return resultList;


    }


    private void generateCombinations(String digits, int currentIndex, StringBuilder currentCombination) {
        if (currentIndex == digits.length()) {
            resultList.add(currentCombination.toString());
            return;
        }

        char currentDigit = digits.charAt(currentIndex);
        String letterOptions = digitToLetters.get(currentDigit);

        if (letterOptions != null) {
            for (int i = 0; i < letterOptions.length(); i++) {
                char letter = letterOptions.charAt(i);
                currentCombination.append(letter);
                generateCombinations(digits, currentIndex + 1, currentCombination);
                currentCombination.deleteCharAt(currentCombination.length() - 1);
            }
        }
    }
}",0,leetcode,NA,JAVA
,"class Solution {
    public boolean isValidSudoku(char[][] board) {
        boolean[][] rows = new boolean[9][9];
        boolean[][] cols = new boolean[9][9];
        boolean[][] boxes = new boolean[9][9];

        for (int i = 0; i < 9; i++) {
            for (int j = 0; j < 9; j++) {
                if (board[i][j] != '.') {
                    int num = board[i][j] - '1';
                    int boxIndex = (i / 3) * 3 + (j / 3);

                    if (rows[i][num] || cols[j][num] || boxes[boxIndex][num]) {
                        return false;
                    }

                    rows[i][num] = cols[j][num] = boxes[boxIndex][num] = true;
                }
            }
        }
        return true;
    }
}",0,leetcode,NA,JAVA
,"import java.util.HashMap;
public class Fibonacci {
    private static HashMap<Integer, Long> memo = new HashMap<>();
    public static long fib(int n) {
        if (n <= 1) return n;
        if (memo.containsKey(n)) return memo.get(n);
        long result = fib(n - 1) + fib(n - 2);
        memo.put(n, result);
        return result;
    }
}
",1,PERPLEXITY,Write a Java Fibonacci function using recursion with HashMap memoization for efficiency,JAVA
,"class Solution {
public:
    string fractionToDecimal(int numerator, int denominator) {
        if (numerator == 0)
            return ""0"";        

        string fraction;
        if ((numerator < 0) ^ (denominator < 0))
            fraction += ""-"";        

        long long dividend = llabs((long long)numerator);
        long long divisor = llabs((long long)denominator);
        fraction += to_string(dividend / divisor);
        long long remainder = dividend % divisor;
        if (remainder == 0) {
            return fraction;
        }

        fraction += ""."";
        unordered_map<long long, int> map;
        while (remainder != 0) {
            if (map.count(remainder)) {
                fraction.insert(map[remainder], ""("");
                fraction += "")"";
                break;
            }
            map[remainder] = fraction.size();
            remainder *= 10;
            fraction += to_string(remainder / divisor);
            remainder %= divisor;
        }

        return fraction;
    }
};",0,leetcode,NA,JAVA
,"class Solution {
    public int numJewelsInStones(String jewels, String stones) 
    {
        int cnt=0;
        for(int i=0;i<stones.length();i++)
        {
            char ch=stones.charAt(i);
            for(int j=0;j<jewels.length();j++)
            {
                if(jewels.charAt(j)==ch) 
                {
                    cnt++;
                    break;
                }
            }
        }
        return cnt;
    }
}",0,leetcode,NA,JAVA
,"class Solution {
    public int maxPoints(int[][] points) {
        int n = points.length;
        if (n <= 2) return n;

        int result = 0;

        for (int i = 0; i < n; i++) {
            Map<String, Integer> map = new HashMap<>();
            int max = 0;

            for (int j = i + 1; j < n; j++) {
                int dx = points[j][0] - points[i][0];
                int dy = points[j][1] - points[i][1];

                int g = gcd(dx, dy);
                dx /= g;
                dy /= g;

                String key = dx + "","" + dy;
                map.put(key, map.getOrDefault(key, 0) + 1);
                max = Math.max(max, map.get(key));
            }

            result = Math.max(result, max + 1); // +1 for anchor point
        }

        return result;
    }

    private int gcd(int a, int b) {
        if (b == 0) return a;
        return gcd(b, a % b);
    }
}",0,leetcode,NA,JAVA
,"import java.util.ArrayList;
public class Stack<T> {
    private ArrayList<T> stack = new ArrayList<>();
    public void push(T item) { stack.add(item); }
    public T pop() { return stack.remove(stack.size() - 1); }
    public T peek() { return stack.get(stack.size() - 1); }
    public boolean isEmpty() { return stack.isEmpty(); }
}
",1,PERPLEXITY,"Implement a generic Stack class in Java using ArrayList with push, pop, peek, and isEmpty methods",JAVA
,"public class Solution {
    public ListNode detectCycle(ListNode head) {
        ListNode slow = head;
        ListNode fast = head;

        while(fast != null && fast.next != null) {
            slow = slow.next;
            fast = fast.next.next;

            if(slow == fast) {
                slow = head;

                while(slow != fast) {
                    slow = slow.next;
                    fast = fast.next;
                }
                return slow;
            }
        }
        return null;
    }
}",0,leetcode,NA,JAVA
,"class ListNode {
    int val; ListNode next;
    ListNode(int val) { this.val = val; }
}
public class LinkedListOps {
    public ListNode reverse(ListNode head) {
        ListNode prev = null, curr = head;
        while (curr != null) {
            ListNode next = curr.next;
            curr.next = prev;
            prev = curr; curr = next;
        }
        return prev;
    }
}
",1,PERPLEXITY,"Write Java code to reverse a singly linked list given a ListNode head, using iterative approach",JAVA
,"public List<String> wordBreak(String s, Set<String> wordDict) {
    return DFS(s, wordDict, new HashMap<String, LinkedList<String>>());
}       

// DFS function returns an array including all substrings derived from s.
List<String> DFS(String s, Set<String> wordDict, HashMap<String, LinkedList<String>>map) {
    if (map.containsKey(s)) 
        return map.get(s);
        
    LinkedList<String>res = new LinkedList<String>();     
    if (s.length() == 0) {
        res.add("""");
        return res;
    }               
    for (String word : wordDict) {
        if (s.startsWith(word)) {
            List<String>sublist = DFS(s.substring(word.length()), wordDict, map);
            for (String sub : sublist) 
                res.add(word + (sub.isEmpty() ? """" : "" "") + sub);               
        }
    }       
    map.put(s, res);
    return res;
}",0,leetcode,NA,JAVA
,"class TreeNode {
    int val; TreeNode left, right;
    TreeNode(int val) { this.val = val; }
}
public class TreeTraversal {
    public void inorder(TreeNode root, List<Integer> result) {
        if (root == null) return;
        inorder(root.left, result);
        result.add(root.val);
        inorder(root.right, result);
    }
}
",1,PERPLEXITY,"Create a Java method for inorder traversal of a binary tree, collecting values in a List",JAVA
,"public RandomListNode copyRandomList(RandomListNode head) {
  RandomListNode iter = head, next;

  // First round: make copy of each node,
  // and link them together side-by-side in a single list.
  while (iter != null) {
    next = iter.next;

    RandomListNode copy = new RandomListNode(iter.label);
    iter.next = copy;
    copy.next = next;

    iter = next;
  }

  // Second round: assign random pointers for the copy nodes.
  iter = head;
  while (iter != null) {
    if (iter.random != null) {
      iter.next.random = iter.random.next;
    }
    iter = iter.next.next;
  }

  // Third round: restore the original list, and extract the copy list.
  iter = head;
  RandomListNode pseudoHead = new RandomListNode(0);
  RandomListNode copy, copyIter = pseudoHead;

  while (iter != null) {
    next = iter.next.next;

    // extract the copy
    copy = iter.next;
    copyIter.next = copy;
    copyIter = copy;

    // restore the original list
    iter.next = next;

    iter = next;
  }

  return pseudoHead.next;
}",0,leetcode,NA,JAVA
,"import java.util.*;

class Solution {
    public List<String> basicCalculatorIV(String expression, String[] evalvars, int[] evalints) {
        Map<String, Integer> evalmap = new HashMap<>();
        for (int i = 0; i < evalvars.length; i++) evalmap.put(evalvars[i], evalints[i]);

        List<String> tokens = tokenize(expression);
        Map<List<String>, Integer> poly = parseExpression(tokens, evalmap);

        List<Map.Entry<List<String>, Integer>> list = new ArrayList<>(poly.entrySet());
        list.sort((a, b) -> {
            if (b.getKey().size() != a.getKey().size()) return b.getKey().size() - a.getKey().size();
            // lexicographic compare by joining with '*'
            return String.join(""*"", a.getKey()).compareTo(String.join(""*"", b.getKey()));
        });

        List<String> ans = new ArrayList<>();
        for (var e : list) {
            int coeff = e.getValue();
            if (coeff == 0) continue;
            StringBuilder sb = new StringBuilder();
            sb.append(coeff);
            for (String v : e.getKey()) sb.append(""*"").append(v);
            ans.add(sb.toString());
        }
        return ans;
    }

    private List<String> tokenize(String expr) {
        List<String> tokens = new ArrayList<>();
        StringBuilder sb = new StringBuilder();
        for (char c : expr.toCharArray()) {
            if (Character.isLetterOrDigit(c)) sb.append(c);
            else {
                if (sb.length() > 0) { tokens.add(sb.toString()); sb.setLength(0); }
                if (c == '+' || c == '-' || c == '*' || c == '(' || c == ')') tokens.add(String.valueOf(c));
            }
        }
        if (sb.length() > 0) tokens.add(sb.toString());
        return tokens;
    }

    private Map<List<String>, Integer> parseExpression(List<String> tokens, Map<String, Integer> evalmap) {
        Deque<Map<List<String>, Integer>> vals = new ArrayDeque<>();
        Deque<String> ops = new ArrayDeque<>();
        Map<String, Integer> prec = Map.of(""+"",1, ""-"",1, ""*"",2);

        for (String tok : tokens) {
            if (tok.equals(""("")) ops.push(tok);
            else if (tok.equals("")"")) {
                while (!ops.peek().equals(""("")) applyOp(vals, ops.pop());
                ops.pop();
            } else if (prec.containsKey(tok)) {
                while (!ops.isEmpty() && prec.containsKey(ops.peek()) && prec.get(ops.peek()) >= prec.get(tok)) {
                    applyOp(vals, ops.pop());
                }
                ops.push(tok);
            } else {
                vals.push(parseToken(tok, evalmap));
            }
        }
        while (!ops.isEmpty()) applyOp(vals, ops.pop());
        return vals.isEmpty() ? new HashMap<>() : vals.pop();
    }

    private void applyOp(Deque<Map<List<String>, Integer>> vals, String op) {
        Map<List<String>, Integer> b = vals.pop();
        Map<List<String>, Integer> a = vals.pop();
        if (op.equals(""+"")) vals.push(add(a, b));
        else if (op.equals(""-"")) vals.push(sub(a, b));
        else vals.push(mul(a, b));
    }

    private Map<List<String>, Integer> parseToken(String tok, Map<String, Integer> evalmap) {
        Map<List<String>, Integer> res = new HashMap<>();
        if (tok.matches(""-?\\d+"")) {
            res.put(Collections.emptyList(), Integer.parseInt(tok));
        } else if (evalmap.containsKey(tok)) {
            res.put(Collections.emptyList(), evalmap.get(tok));
        } else {
            res.put(Arrays.asList(tok), 1);
        }
        return res;
    }

    private Map<List<String>, Integer> combine(Map<List<String>, Integer> m) {
        Map<List<String>, Integer> res = new HashMap<>();
        for (var e : m.entrySet()) {
            if (e.getValue() != 0) res.put(e.getKey(), res.getOrDefault(e.getKey(), 0) + e.getValue());
        }
        res.entrySet().removeIf(kv -> kv.getValue() == 0);
        return res;
    }

    private Map<List<String>, Integer> add(Map<List<String>, Integer> a, Map<List<String>, Integer> b) {
        Map<List<String>, Integer> res = new HashMap<>(a);
        for (var e : b.entrySet()) res.put(e.getKey(), res.getOrDefault(e.getKey(), 0) + e.getValue());
        return combine(res);
    }

    private Map<List<String>, Integer> sub(Map<List<String>, Integer> a, Map<List<String>, Integer> b) {
        Map<List<String>, Integer> res = new HashMap<>(a);
        for (var e : b.entrySet()) res.put(e.getKey(), res.getOrDefault(e.getKey(), 0) - e.getValue());
        return combine(res);
    }

    private Map<List<String>, Integer> mul(Map<List<String>, Integer> a, Map<List<String>, Integer> b) {
        Map<List<String>, Integer> res = new HashMap<>();
        for (var ea : a.entrySet()) {
            for (var eb : b.entrySet()) {
                List<String> merged = new ArrayList<>(ea.getKey());
                merged.addAll(eb.getKey());
                Collections.sort(merged);
                res.put(merged, res.getOrDefault(merged, 0) + ea.getValue() * eb.getValue());
            }
        }
        return combine(res);
    }
}",0,leetcode,NA,JAVA
,"class Solution {
    public Node cloneGraph(Node node) {
        if (node == null) return null;
        Map<Node, Node> copiedMap = new HashMap<>();
        bfs(node, copiedMap);
        return copiedMap.get(node);
    }

    private void bfs(Node startNode, Map<Node, Node> copiedMap) {
        Queue<Node> queue = new ArrayDeque<>(); // include nodes that have been visited (copied) only

        // check & copy node at Generation
        copiedMap.put(startNode, new Node(startNode.val));
        queue.offer(startNode);

        while (!queue.isEmpty()) {
            Node node = queue.poll();

            // copy & link, add neighbors to Queue
            for (Node neighbor: node.neighbors) {
                // check & copy node at Generation
                if (copiedMap.containsKey(neighbor)) { // neighbor is already visited (copied), just link
                    // IMPORTANT: DON'T JUST CONTINUE!
                    copiedMap.get(node).neighbors.add(copiedMap.get(neighbor));
                } else { // copy, link, add neighbor to queue to be visited
                    copiedMap.put(neighbor, new Node(neighbor.val));
                    queue.offer(neighbor);
                    copiedMap.get(node).neighbors.add(copiedMap.get(neighbor));
                }
                
            }
        }
    }
}",0,leetcode,NA,JAVA

,"class Solution {
    public List<Integer> findDisappearedNumbers(int[] nums) {
        Set<Integer> numSet = new HashSet<>();
        for (int num : nums) {
            numSet.add(num);
        }
        
        List<Integer> result = new ArrayList<>();
        for (int i = 1; i <= nums.length; i++) {
            if (!numSet.contains(i)) {
                result.add(i);
            }
        }
        
        return result;        
    }
}",0,leetcode,NA,JAVA

,"class Solution {
    public int longestConsecutive(int[] nums) {
        HashSet<Integer> set = new HashSet<>();
        
        if(nums.length==0){
            return 0;
        }

        for(int i : nums){
            set.add(i);
        }
        int max = 0;
        for(int i : nums){
            if(!set.contains(i)){
                continue;
            }
            int n = i;
            int m = i;
            int length = 1;
            while(set.contains(n+1)){
                n=(n+1);
                set.remove(n);
                length++;
            }
            while(set.contains(m-1)){
                m= m-1;
                set.remove(m);
                length++;
            }
            max = Math.max(length, max);
        }
        return max;
    }
}",0,leetcode,NA,JAVA

,"public class PalindromeChecker {
    public static boolean isPalindrome(String s) {
        s = s.toLowerCase().replaceAll(""[^a-z0-9]"", """");
        int left = 0, right = s.length() - 1;
        while (left < right) {
            if (s.charAt(left++) != s.charAt(right--)) return false;
        }
        return true;
    }
}
",1,PERPLEXITY,"Write a Java static method to check if a string is a palindrome, ignoring case and non-alphanumeric chars.",JAVA

,"// Simple BFS approach (can TLE on large inputs)
class Solution {
    public List<List<String>> findLadders(String beginWord, String endWord, List<String> wordList) {
        Queue<List<String>> q = new ArrayDeque<>();
        Set<String> set = new HashSet<>(wordList);
        List<List<String>> ans = new ArrayList<>();

        if (!set.contains(endWord)) return ans;

        q.add(new ArrayList<>(List.of(beginWord)));
        boolean found = false;

        while (!q.isEmpty() && !found) {
            int size = q.size();
            Set<String> used = new HashSet<>();

            for (int k = 0; k < size; k++) {
                List<String> path = q.poll();
                String last = path.get(path.size() - 1);

                if (last.equals(endWord)) {
                    ans.add(path);
                    found = true;
                }

                char[] arr = last.toCharArray();
                for (int i = 0; i < arr.length; i++) {
                    char original = arr[i];
                    for (char c = 'a'; c <= 'z'; c++) {
                        if (c == original) continue;
                        arr[i] = c;
                        String next = new String(arr);

                        if (set.contains(next)) {
                            List<String> newPath = new ArrayList<>(path);
                            newPath.add(next);
                            q.add(newPath);
                            used.add(next);
                        }
                    }
                    arr[i] = original;
                }
            }
            for (String w : used) set.remove(w);
        }
        return ans;
    }
}",0,leetcode,NA,JAVA

,"import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
public class DateUtil {
    public static String format(LocalDate date) {
        DateTimeFormatter fmt = DateTimeFormatter.ofPattern(""yyyy-MM-dd"");
        return date.format(fmt);
    }
}
",1,PERPLEXITY,Create a Java utility class with a method to format LocalDate as yyyy-MM-dd string,JAVA

,"class Solution {
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        Deque<Integer> preorderQueue = new ArrayDeque<>();
        for (int val : preorder) {
            preorderQueue.offer(val);
        }

        return build(preorderQueue, inorder);        
    }

    private TreeNode build(Deque<Integer> preorder, int[] inorder) {
        if (inorder.length > 0) {
            int idx = indexOf(inorder, preorder.poll());
            TreeNode root = new TreeNode(inorder[idx]);

            root.left = build(preorder, Arrays.copyOfRange(inorder, 0, idx));
            root.right = build(preorder, Arrays.copyOfRange(inorder, idx + 1, inorder.length));

            return root;
        }
        return null;
    }

    private int indexOf(int[] arr, int value) {
        for (int i = 0; i < arr.length; i++) {
            if (arr[i] == value) {
                return i;
            }
        }
        return -1; // shouldn't happen with valid input
    }    
}",0,leetcode,NA,JAVA
,"class Person {
    String name; int age;
    Person(String name, int age) { this.name = name; this.age = age; }
}
class Employee extends Person {
    String dept; double salary;
    Employee(String n, int a, String d, double s) {
        super(n, a); dept = d; salary = s;
    }
}
",1,PERPLEXITY,"Define Java classes Person and Employee with inheritance, constructor chaining, and fields name, age, dept, salary",JAVA
,"class Solution {
    public String minWindow(String s, String t) {
        
        if (s == null || t == null || s.length() == 0 || t.length() == 0 ||
                s.length() < t.length()) {
            return new String();
        }

        int left = 0;
        int right = 0;
        int windowFreqArr[] = new int[256];
        int targetFreqArr[] = new int[256];
        int startIdx = -1;
        int minLength = Integer.MAX_VALUE; 

        for (int i = 0; i < t.length(); i++) {
            char ch = t.charAt(i);
            targetFreqArr[ch]++;
        }
        int required = t.length();

        for (right = 0; right < s.length(); right++) {
            char rightChar = s.charAt(right);
            windowFreqArr[rightChar]++;
            
            // If this character is needed (count > 0), decrement required
            if (targetFreqArr[rightChar] > 0) {
                required--; // One less character needed
            }
            targetFreqArr[rightChar]--;

            // When we have all characters, try to minimize window
            while (required == 0) {
                int length = right - left + 1;
                if (length < minLength) {
                    minLength = length;
                    startIdx = left;
                }
                
                // increment the left
                char leftChar = s.charAt(left);
                windowFreqArr[leftChar]--;
                left++;

                // If a needed character is removed, window becomes invalid
                targetFreqArr[leftChar]++;
                if (targetFreqArr[leftChar] > 0) {
                    required++; // We now need this character again
                }
            }
        }

        return startIdx == -1 ? """" : s.substring(startIdx, startIdx + minLength);
    }

}",0,leetcode,NA,JAVA
,"class Solution {
    public String reorganizeString(String s) {
        // count ch
        Map<Character, Integer> freq = new HashMap<>();
        for (char ch : s.toCharArray()) {
            freq.put(ch, freq.getOrDefault(ch, 0) + 1);
        }

        // sort by cnt
        List<Map.Entry<Character, Integer>> list = new ArrayList<>(freq.entrySet());
        list.sort((a,b) -> b.getValue() - a.getValue());

        // create buckets of str
        int maxFreq = list.get(0).getValue();
        StringBuilder[] buckets = new StringBuilder[maxFreq];

        // iterate over ch and cnts and fill buckets in circular fashion
        int k = 0; // bucket ind
        for (int i = 0; i < freq.size(); i++) {
            for (int j = 0; j < list.get(i).getValue(); j++) {
                int id = k % maxFreq;
                if (buckets[id] == null) buckets[id] = new StringBuilder();
                buckets[id].append(list.get(i).getKey());
                k++;
            }
        }

        // merge
        StringBuilder res = new StringBuilder();
        for (StringBuilder sb : buckets) {
            res.append(sb);
        }

        String resStr = res.toString();

        // validate

        for (int i = 0; i < resStr.length() - 1; i++) {
            if (resStr.charAt(i) == resStr.charAt(i+1)) return """";
        }

        return resStr;
    }
}


// ababb

// bbbb
// cccc - 3

// aaa
// bbb

// ca cb cx c

// abcabccc

// c

// abcdabcdabcdddddddd",0,leetcode,NA,JAVA
,"public class Solution {
public void setZeroes(int[][] matrix) {
    boolean fr = false,fc = false;
    for(int i = 0; i < matrix.length; i++) {
        for(int j = 0; j < matrix[0].length; j++) {
            if(matrix[i][j] == 0) {
                if(i == 0) fr = true;
                if(j == 0) fc = true;
                matrix[0][j] = 0;
                matrix[i][0] = 0;
            }
        }
    }
    for(int i = 1; i < matrix.length; i++) {
        for(int j = 1; j < matrix[0].length; j++) {
            if(matrix[i][0] == 0 || matrix[0][j] == 0) {
                matrix[i][j] = 0;
        }}
    }
    if(fr) {
        for(int j = 0; j < matrix[0].length; j++) {
            matrix[0][j] = 0;
        }
    }
    if(fc) {
        for(int i = 0; i < matrix.length; i++) {
            matrix[i][0] = 0;
        }
    }
}}  ",0,leetcode,NA,JAVA
,,,leetcode,NA,JAVA
,"public class Solution {
    private static final Map<Character, Integer> A = new HashMap<>();
    static { A.put('A',0); A.put('C',1); A.put('G',2); A.put('T',3); }
    private final int A_SIZE_POW_9 = (int) Math.pow(A.size(), 9);

    public List<String> findRepeatedDnaSequences(String s) {
        Set<String> res = new HashSet<>();
        Set<Integer> hashes = new HashSet<>();
        for (int i = 0, rhash = 0; i < s.length(); i++) {
            if (i > 9) rhash -= A_SIZE_POW_9 * A.get(s.charAt(i-10));
            rhash = A.size() * rhash + A.get(s.charAt(i));
            if (i > 8 && !hashes.add(rhash)) res.add(s.substring(i-9,i+1));
        }
        return new ArrayList<>(res);
    }
}",0,leetcode,NA,JAVA
,"public class QuickSort {
    public static void sort(int[] arr, int low, int high) {
        if (low < high) {
            int pi = partition(arr, low, high);
            sort(arr, low, pi - 1);
            sort(arr, pi + 1, high);
        }
    }
    private static int partition(int[] arr, int low, int high) {
        int pivot = arr[high];
        int i = low - 1;
        for (int j = low; j < high; j++) {
            if (arr[j] <= pivot) {
                i++;
                int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp;
            }
        }
        int temp = arr[i + 1]; arr[i + 1] = arr[high]; arr[high] = temp;
        return i + 1;
    }
}
",1,PERPLEXITY,Write a Java quicksort algorithm to sort an integer array in-place using the Lomuto partition scheme,JAVA
,"class Trie {
    Node root;

    public Trie() {
        root = new Node();
    }
    
    public void insert(String word) {
        root.insert(word, 0);
    }
    
    public boolean search(String word) {
        return root.search(word, 0);
    }
    
    public boolean startsWith(String prefix) {
        return root.startsWith(prefix, 0);
    }

    class Node {
        Node[] nodes;
        boolean isEnd;

        Node() {
            nodes = new Node[26];
        }

        private void insert(String word, int idx) {
            if (idx >= word.length()) return;
            int i = word.charAt(idx) - 'a';
            if (nodes[i] == null) {
                nodes[i] = new Node();
            }

            if (idx == word.length()-1) nodes[i].isEnd = true;
            nodes[i].insert(word, idx+1);
        }

        private boolean search(String word, int idx) {
            if (idx >= word.length()) return false;
            Node node = nodes[word.charAt(idx) - 'a'];
            if (node == null) return false;
            if (idx == word.length() - 1 && node.isEnd) return true;

            return node.search(word, idx+1);

        }

        private boolean startsWith(String prefix, int idx) {
            if (idx >= prefix.length()) return false;
            Node node = nodes[prefix.charAt(idx) - 'a'];
            if (node == null) return false;
            if (idx == prefix.length() - 1) return true;

            return node.startsWith(prefix, idx+1);
        }
    }
}",0,leetcode,NA,JAVA
,"class Solution {
    public String[] findRestaurant(String[] list1, String[] list2) {
        int min = 10000;
        ArrayList<String> arr = new ArrayList<>();
        for (int i = 0; i < list1.length; i++)
            for (int j = 0; j < list2.length; j++)
                if (list1[i].equals(list2[j])) {
                    if (i + j <= min) {
                        if (i + j < min) {
                            arr.clear();
                            min = i + j;
                        }
                        arr.add(list1[i]);
                    }
                    break;
                }
        return arr.toArray(new String[0]);
    }
}",0,leetcode,NA,JAVA
,"class Solution {
    public List<Integer> majorityElement(int[] nums) {
        // Create a frequency map to store the count of each element
        Map<Integer, Integer> elementCountMap = new HashMap<>();
        
        // Iterate through the input array to count element occurrences
        for (int i = 0; i < nums.length; i++) {
            elementCountMap.put(nums[i], elementCountMap.getOrDefault(nums[i], 0) + 1);
        }
        
        List<Integer> majorityElements = new ArrayList<>();
        int threshold = nums.length / 3;
        
        // Iterate through the frequency map to identify majority elements
        for (Map.Entry<Integer, Integer> entry : elementCountMap.entrySet()) {
            int element = entry.getKey();
            int count = entry.getValue();
            
            // Check if the element count is greater than the threshold
            if (count > threshold) {
                majorityElements.add(element);
            }
        }
        
        return majorityElements;
    }
}",0,leetcode,NA,JAVA
,"public class MergeArrays {
    public static int[] merge(int[] a, int[] b) {
        int[] result = new int[a.length + b.length];
        int i = 0, j = 0, k = 0;
        while (i < a.length && j < b.length) {
            if (a[i] <= b[j]) result[k++] = a[i++];
            else result[k++] = b[j++];
        }
        while (i < a.length) result[k++] = a[i++];
        while (j < b.length) result[k++] = b[j++];
        return result;
    }
}
",1,PERPLEXITY,Create a Java method that merges two sorted integer arrays into one sorted array without extra space if possible.,JAVA
,"class Solution {
    public int nthUglyNumber(int n) {
        int[] primes = {2, 3, 5};
        PriorityQueue<Long> uglyHeap = new PriorityQueue<>();
        HashSet<Long> visited = new HashSet<>();
        
        uglyHeap.add(1L);
        visited.add(1L);
        
        long curr = 1L;
        for (int i = 0; i < n; i++) {
            curr = uglyHeap.poll();
            for (int prime : primes) {
                long new_ugly = curr * prime;
                if (!visited.contains(new_ugly)) {
                    uglyHeap.add(new_ugly);
                    visited.add(new_ugly);
                }
            }
        }
        return (int)curr;
    }
}",0,leetcode,NA,JAVA
,"public class FactorialDP {
    public static long factorial(int n) {
        if (n <= 1) return 1;
        long[] dp = new long[n + 1];
        dp[0] = dp[1] = 1;
        for (int i = 2; i <= n; i++) {
            dp[i] = dp[i - 1] * i;
        }
        return dp[n];
    }
}
",1,PERPLEXITY,Implement a Java dynamic programming solution to compute factorial of a large number using an array.,JAVA
,"class Solution {
    public int missingNumber(int[] nums) {
        int n = nums.length;
        int[] v = new int[n+1];
        Arrays.fill(v, -1);
        for(int i = 0; i < nums.length; i++) {
            v[nums[i]] = nums[i];
        }
        for(int i = 0; i < v.length; i++) {
            if(v[i] == -1) return i;
        }
        return 0;
    }
}
",0,leetcode,NA,JAVA
,"public class PrimeChecker {
    public static boolean isPrime(long n) {
        if (n <= 1) return false;
        if (n <= 3) return true;
        if (n % 2 == 0 || n % 3 == 0) return false;
        for (long i = 5; i * i <= n; i += 6) {
            if (n % i == 0 || n % (i + 2) == 0) return false;
        }
        return true;
    }
}
",1,PERPLEXITY,"Write an efficient Java method to check if a number is prime, optimized for large inputs.",JAVA
,"class Solution {
    public boolean isIsomorphic(String s, String t) {
        HashMap<Character, Integer> charIndexS = new HashMap<>();
        HashMap<Character, Integer> charIndexT = new HashMap<>();

        for (int i = 0; i < s.length(); i++) {
            if (!charIndexS.containsKey(s.charAt(i))) {
                charIndexS.put(s.charAt(i), i);
            }

            if (!charIndexT.containsKey(t.charAt(i))) {
                charIndexT.put(t.charAt(i), i);
            }

            if (!charIndexS.get(s.charAt(i)).equals(charIndexT.get(t.charAt(i)))) {
                return false;
            }
        }

        return true;        
    }
}",0,leetcode,NA,JAVA
,"class Solution {
    public List<Integer> partitionLabels(String s) {
        Map<Character, Integer> lastOccurrence = new HashMap<>();
        for (int i = 0; i < s.length(); i++) {
            lastOccurrence.put(s.charAt(i), i);
        }

        List<Integer> result = new ArrayList<>();
        int start = 0, end = 0;

        for (int i = 0; i < s.length(); i++) {
            end = Math.max(end, lastOccurrence.get(s.charAt(i)));
            if (i == end) {
                result.add(end - start + 1);
                start = i + 1;
            }
        }

        return result;
    }
}",0,leetcode,NA,JAVA
,"class Solution {
    public boolean wordPattern(String pattern, String s) {
        
        String[] words = s.split("" "");

        if (pattern.length() != words.length) return false;

        Map<Character, String> charWord = new HashMap<>();
        Map<String, Character> wordChar = new HashMap<>();

        for (int i = 0; i < pattern.length(); i++) {
            char ch = pattern.charAt(i);
            String word = words[i];

            if (charWord.containsKey(ch)) {
                if (!charWord.get(ch).equals(word)) {
                    return false;
                }
            } else if (wordChar.containsKey(word)) {
                return false;
            } else {
                charWord.put(ch, word);
                wordChar.put(word, ch);
            }
        }

        return true;
    }
}",0,leetcode,NA,JAVA
,"class Solution {
    public String frequencySort(String s) {
         Map<Character, Integer> freqMap = new HashMap<>();
        for (char c : s.toCharArray()) {
            freqMap.put(c, freqMap.getOrDefault(c, 0) + 1);
        }

        
        List<Map.Entry<Character, Integer>> list =
                new ArrayList<>(freqMap.entrySet());

        
        list.sort((a, b) -> b.getValue() - a.getValue());

        
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<Character, Integer> entry : list) {
            char ch = entry.getKey();
            int count = entry.getValue();
            for (int i = 0; i < count; i++) {
                sb.append(ch);
            }
        }

        return sb.toString();
    }
}




    ",0,leetcode,NA,JAVA
,"// With comments
class RandomizedCollection {
    private Map<Integer, Set<Integer>> map; // Map to store values and their indices in the list
    private List<Integer> list; // List to store the values in the order they were inserted

    public RandomizedCollection() {
        this.map = new HashMap<>();
        this.list = new ArrayList<>();
    }

    // Inserts a value into the collection, returns true if the value was not present before
    public boolean insert(int val) {
        boolean ans = map.containsKey(val); // Check if the value is already present
        map.computeIfAbsent(val, key -> new HashSet<>()).add(list.size()); // Add the index to the set in the map
        list.add(val); // Add the value to the list
        return !ans; // Return true if the value was not present before
    }

    // Removes a value from the collection, returns true if the value was present
    public boolean remove(int val) {
        if (!map.containsKey(val)) return false; // If the value is not present, return false

        int indexVal = map.get(val).iterator().next(); // Get one of the indices of the value

        map.get(val).remove(indexVal); // Remove the index from the set in the map
        if (map.get(val).isEmpty()) map.remove(val); // If the set is empty, remove the value from the map

        if (indexVal != list.size() - 1) {
            // If the index to be removed is not the last index in the list

            // Update the map for the last value in the list
            map.get(list.get(list.size() - 1)).remove(list.size() - 1);
            map.get(list.get(list.size() - 1)).add(indexVal);

            list.set(indexVal, list.get(list.size() - 1)); // Replace the value at indexVal with the last value
        }

        list.remove(list.size() - 1); // Remove the last element from the list
        return true; // Return true since the value was present and removed
    }

    // Returns a random element from the collection
    public int getRandom() {
        Random random = new Random();
        int ind = random.nextInt(list.size()); // Generate a random index
        return list.get(ind); // Return the value at the random index
    }
}",0,leetcode,NA,JAVA
,"import java.util.Arrays;
public class AnagramDetector {
    public static boolean areAnagrams(String s1, String s2) {
        s1 = s1.toLowerCase().replaceAll(""\\s"", """");
        s2 = s2.toLowerCase().replaceAll(""\\s"", """");
        if (s1.length() != s2.length()) return false;
        char[] a1 = s1.toCharArray(); char[] a2 = s2.toCharArray();
        Arrays.sort(a1); Arrays.sort(a2);
        return Arrays.equals(a1, a2);
    }
}
",1,PERPLEXITY,"Create a Java function to detect if two strings are anagrams, ignoring case and spaces.",JAVA
,"

class RandomizedSet {
    private ArrayList<Integer> list;
    private Map<Integer, Integer> map;

    public RandomizedSet() {
        list = new ArrayList<>();
        map = new HashMap<>();
    }

    public boolean search(int val) {
        return map.containsKey(val);
    }

    public boolean insert(int val) {
        if (search(val)) return false;

        list.add(val);
        map.put(val, list.size() - 1);
        return true;
    }

    public boolean remove(int val) {
        if (!search(val)) return false;

        int index = map.get(val);
        list.set(index, list.get(list.size() - 1));
        map.put(list.get(index), index);
        list.remove(list.size() - 1);
        map.remove(val);

        return true;
    }

    public int getRandom() {
        Random rand = new Random();
        return list.get(rand.nextInt(list.size()));
    }
}

",0,leetcode,NA,JAVA
,"import java.util.LinkedList;
public class Queue<T> {
    private LinkedList<T> list = new LinkedList<>();
    public void enqueue(T item) { list.addLast(item); }
    public T dequeue() { return list.pollFirst(); }
    public T peek() { return list.peekFirst(); }
    public int size() { return list.size(); }
    public boolean isEmpty() { return list.isEmpty(); }
}
",1,PERPLEXITY,"Implement a generic Queue class in Java using LinkedList with enqueue, dequeue, and size methods.",JAVA
,"class Twitter {
    private static int timestamp = 0;
    private Map<Integer, List<int[]>> tweets = new HashMap<>();
    private Map<Integer, Set<Integer>> followMap = new HashMap<>();

    public void postTweet(int userId, int tweetId) {
        tweets.putIfAbsent(userId, new ArrayList<>());
        tweets.get(userId).add(new int[]{timestamp++, tweetId});
    }

    public List<Integer> getNewsFeed(int userId) {
        PriorityQueue<int[]> maxHeap = new PriorityQueue<>((a, b) -> b[0] - a[0]);
        Set<Integer> followees = followMap.getOrDefault(userId, new HashSet<>());
        followees.add(userId);

        for (int followee : followees) {
            List<int[]> tweetList = tweets.getOrDefault(followee, new ArrayList<>());
            maxHeap.addAll(tweetList);
        }

        List<Integer> res = new ArrayList<>();
        while (!maxHeap.isEmpty() && res.size() < 10) {
            res.add(maxHeap.poll()[1]);
        }
        return res;
    }

    public void follow(int followerId, int followeeId) {
        followMap.putIfAbsent(followerId, new HashSet<>());
        followMap.get(followerId).add(followeeId);
    }

    public void unfollow(int followerId, int followeeId) {
        if (followMap.containsKey(followerId)) {
            followMap.get(followerId).remove(followeeId);
        }
    }
}",0,leetcode,NA,JAVA
,"public class CustomEntry<K, V> {
    private K key;
    private V value;
    private CustomEntry<K, V> next;
    public CustomEntry(K key, V value) {
        this.key = key; this.value = value;
    }
    public K getKey() { return key; }
    public V getValue() { return value; }
    public void setValue(V value) { this.value = value; }
    public CustomEntry<K, V> getNext() { return next; }
    public void setNext(CustomEntry<K, V> next) { this.next = next; }
}
",1,PERPLEXITY,Define a custom Entry class for Java HashMap-like structure with key-value pairs.,JAVA
,"class Solution {
    public int[] intersect(int[] nums1, int[] nums2) {
        int l1 = nums1.length;
        int l2 = nums2.length;
        int i = 0, j = 0, k = 0;
        Arrays.sort(nums1);
        Arrays.sort(nums2);
        while( i < l1 && j < l2)
        {
            if(nums1[i] < nums2[j])
            {
                i++;
            }
            else if(nums1[i] > nums2[j])
            {
                j++;
            }
            else
            {
                nums1[k++] = nums1[i++];
                j++;
            }
        }
        return Arrays.copyOfRange(nums1,0,k);
    }
}",0,leetcode,NA,JAVA
,"class TreeNode {
    int val; TreeNode left, right;
    TreeNode(int val) { this.val = val; }
}
public class BSTInsert {
    public TreeNode insert(TreeNode root, int val) {
        if (root == null) return new TreeNode(val);
        TreeNode curr = root;
        while (true) {
            if (val < curr.val) {
                if (curr.left == null) { curr.left = new TreeNode(val); break; }
                curr = curr.left;
            } else {
                if (curr.right == null) { curr.right = new TreeNode(val); break; }
                curr = curr.right;
            }
        }
        return root;
    }
}
",1,PERPLEXITY,Write Java code for inserting a node into a Binary Search Tree iteratively,JAVA
,"public List<Integer> topKFrequent(int[] nums, int k) {

        List<Integer>[] bucket = new List[nums.length + 1];
        Map<Integer, Integer> frequencyMap = new HashMap<Integer, Integer>();

        for (int n : nums) {
                frequencyMap.put(n, frequencyMap.getOrDefault(n, 0) + 1);
        }

        for (int key : frequencyMap.keySet()) {
                int frequency = frequencyMap.get(key);
                if (bucket[frequency] == null) {
                        bucket[frequency] = new ArrayList<>();
                }
                bucket[frequency].add(key);
        }

        List<Integer> res = new ArrayList<>();

        for (int pos = bucket.length - 1; pos >= 0 && res.size() < k; pos--) {
                if (bucket[pos] != null) {
                        res.addAll(bucket[pos]);
                }
        }
        return res;
}",0,leetcode,NA,JAVA
,"class Solution {
    public boolean pyramidTransition(String bottom, List<String> allowed) {
        List<Character>[][] map = new List[6][6];
        Map<String, Boolean> memo = new HashMap<>();
        
        for (String al : allowed) {
            int a = al.charAt(0) - 'A';
            int b = al.charAt(1) - 'A';
            if (map[a][b] == null) map[a][b] = new ArrayList<>();
            map[a][b].add(al.charAt(2));
        }
        
        return dfs(bottom.toCharArray(), map, memo);
    }
    
    private boolean dfs(char[] row, List<Character>[][] map, Map<String, Boolean> memo) {
        int n = row.length;
        if (n == 1) return true;
        
        String key = new String(row);
        if (memo.containsKey(key)) return memo.get(key);
        
        List<char[]> nextRows = new ArrayList<>();
        getNextRows(row, map, 0, new char[n-1], nextRows);
        
        for (char[] next : nextRows) {
            if (dfs(next, map, memo)) {
                memo.put(key, true);
                return true;
            }
        }
        
        memo.put(key, false);
        return false;
    }
    
    private void getNextRows(char[] row, List<Character>[][] map, int idx, 
                            char[] current, List<char[]> result) {
        if (idx == row.length - 1) {
            result.add(current.clone());
            return;
        }
        
        int a = row[idx] - 'A';
        int b = row[idx + 1] - 'A';
        
        if (map[a][b] == null) return;
        
        for (char c : map[a][b]) {
            current[idx] = c;
            getNextRows(row, map, idx + 1, current, result);
        }
    }
}",0,leetcode,NA,JAVA
,"public class Solution {
public List<List<Integer>> palindromePairs(String[] words) {
    List<List<Integer>> res = new ArrayList<List<Integer>>();
    if(words == null || words.length == 0){
        return res;
    }
    //build the map save the key-val pairs: String - idx
    HashMap<String, Integer> map = new HashMap<>();
    for(int i = 0; i < words.length; i++){
        map.put(words[i], i);
    }
    
    //special cases: """" can be combine with any palindrome string
    if(map.containsKey("""")){
        int blankIdx = map.get("""");
        for(int i = 0; i < words.length; i++){
            if(isPalindrome(words[i])){
                if(i == blankIdx) continue;
                res.add(Arrays.asList(blankIdx, i));
                res.add(Arrays.asList(i, blankIdx));
            }
        }
    }
    
    //find all string and reverse string pairs
    for(int i = 0; i < words.length; i++){
        String cur_r = reverseStr(words[i]);
        if(map.containsKey(cur_r)){
            int found = map.get(cur_r);
            if(found == i) continue;
            res.add(Arrays.asList(i, found));
        }
    }
    
    //find the pair s1, s2 that 
    //case1 : s1[0:cut] is palindrome and s1[cut+1:] = reverse(s2) => (s2, s1)
    //case2 : s1[cut+1:] is palindrome and s1[0:cut] = reverse(s2) => (s1, s2)
    for(int i = 0; i < words.length; i++){
        String cur = words[i];
        for(int cut = 1; cut < cur.length(); cut++){
            if(isPalindrome(cur.substring(0, cut))){
                String cut_r = reverseStr(cur.substring(cut));
                if(map.containsKey(cut_r)){
                    int found = map.get(cut_r);
                    if(found == i) continue;
                    res.add(Arrays.asList(found, i));
                }
            }
            if(isPalindrome(cur.substring(cut))){
                String cut_r = reverseStr(cur.substring(0, cut));
                if(map.containsKey(cut_r)){
                    int found = map.get(cut_r);
                    if(found == i) continue;
                    res.add(Arrays.asList(i, found));
                }
            }
        }
    }
    
    return res;
}

public String reverseStr(String str){
    StringBuilder sb= new StringBuilder(str);
    return sb.reverse().toString();
}

public boolean isPalindrome(String s){
    int i = 0;
    int j = s.length() - 1;
    while(i <= j){
        if(s.charAt(i) != s.charAt(j)){
            return false;
        }
        i++;
        j--;
    }
    return true;
}",0,leetcode,NA,JAVA
,"import java.util.*;
public class Graph {
    private List<List<Integer>> adjList;
    public Graph(int vertices) {
        adjList = new ArrayList<>();
        for (int i = 0; i < vertices; i++) {
            adjList.add(new ArrayList<>());
        }
    }
    public void addEdge(int u, int v) {
        adjList.get(u).add(v);
        adjList.get(v).add(u); // undirected
    }
    public List<Integer> getNeighbors(int v) {
        return adjList.get(v);
    }
}
",1,PERPLEXITY,Create a Java graph representation using adjacency list with List<List<Integer>>,JAVA
,"public String getHint(String secret, String guess) {
    int bulls = 0;
    int cows = 0;
    int[] numbers = new int[10];
    for (int i = 0; i<secret.length(); i++) {
        int s = Character.getNumericValue(secret.charAt(i));
        int g = Character.getNumericValue(guess.charAt(i));
        if (s == g) bulls++;
        else {
            if (numbers[s] < 0) cows++;
            if (numbers[g] > 0) cows++;
            numbers[s] ++;
            numbers[g] --;
        }
    }
    return bulls + ""A"" + cows + ""B"";
}",0,leetcode,NA,JAVA
,"public class MinHeapPQ {
    private int[] heap;
    private int size;
    public MinHeapPQ(int capacity) {
        heap = new int[capacity];
        size = 0;
    }
    private void heapifyUp(int index) {
        while (index > 0 && heap[(index - 1) / 2] > heap[index]) {
            swap((index - 1) / 2, index);
            index = (index - 1) / 2;
        }
    }
    private void heapifyDown(int index) {
        int smallest = index;
        int left = 2 * index + 1; int right = 2 * index + 2;
        if (left < size && heap[left] < heap[smallest]) smallest = left;
        if (right < size && heap[right] < heap[smallest]) smallest = right;
        if (smallest != index) { swap(index, smallest); heapifyDown(smallest); }
    }
    private void swap(int i, int j) { int temp = heap[i]; heap[i] = heap[j]; heap[j] = temp; }
}
",1,PERPLEXITY,Implement a min-heap priority queue in Java for integers using an array,JAVA
,"class Solution {
    public String frequencySort(String s) {
        char str[] = s.toCharArray();
        HashMap<Character,Integer> map = new HashMap<>();
        for(char n:str){
            map.put(n, map.getOrDefault(n, 0) + 1);
        }
        ArrayList<Character> list = new ArrayList<>(map.keySet());
        Collections.sort(list, (a, b) -> map.get(b) - map.get(a));
        StringBuilder sb = new StringBuilder();
        for(char ch:list){
            for(int i = 0; i < map.get(ch); i++){
                sb.append(ch);
            }
        }
        return sb.toString();
    }
}",0,leetcode,NA,JAVA
,"import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.URI;
public class HttpGetClient {
    public static String get(String url) throws Exception {
        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder()
            .uri(URI.create(url))
            .GET()
            .build();
        HttpResponse<String> response = client.send(request, 
            HttpResponse.BodyHandlers.ofString());
        return response.body();
    }
}
",1,PERPLEXITY,Write a Java method using HttpClient to make a GET request and return the response body as string,JAVA
,"public int numberOfBoomerangs(int[][] points) {
                if(points == null || points.length == 0 || points[0].length == 0){
                        return 0;
                }
                int count = 0;
                Map<Integer,Integer> hashMap = new HashMap<>();
                for (int i = 0;i < points.length;i++){
                        //count distances for every i with an empty hashMap,and hashMap.clear() is more faster than new HashMap()
                        hashMap.clear();
                        for (int j = 0;j < points.length;j++){
                                //it's unnecessary when i == j
                                if (i == j){
                                        continue;
                                }
                                //multiple them directly is more faster than use Math.pow()
                                int distance = (points[j][0]-points[i][0])*(points[j][0]-points[i][0]) + (points[j][1]-points[i][1]) * (points[j][1]-points[i][1]);
                                //First, select one position to place your new point by distance with number of hashMap.get(distance)
                                //and then you can change the order of the two elements,so multiple 2
                                count += hashMap.getOrDefault(distance,0) * 2;
                                hashMap.put(distance,hashMap.getOrDefault(distance,0) + 1);
                        }
                }
                return count;
        }",0,leetcode,NA,JAVA

,"import java.util.Base64;
public class Base64Util {
    public static String encode(String input) {
        byte[] encoded = Base64.getEncoder().encode(input.getBytes());
        return new String(encoded);
    }
    public static String decode(String encoded) {
        byte[] decoded = Base64.getDecoder().decode(encoded.getBytes());
        return new String(decoded);
    }
}
",1,PERPLEXITY,Create a Java utility class with static methods to encode and decode strings using Base64.,JAVA

,"class Solution {
    public List<Integer> findDuplicates(int[] nums) {
        List<Integer> ans = new ArrayList<>();
        int n = nums.length;

        for (int i = 0; i < n; i++) {
            int num = Math.abs(nums[i]);
            if (nums[num - 1] > 0) {
                nums[num - 1] *= -1;
            } else {
                ans.add(num);
            }
        }
        return ans;
    }
}",0,leetcode,NA,JAVA

,"import java.util.regex.Pattern;
public class EmailValidator {
    private static final Pattern EMAIL_PATTERN = 
        Pattern.compile(""^[A-Za-z0-9+_.-]+@([A-Za-z0-9.-]+\\.[A-Za-z]{2,})$"");
    public static boolean isValid(String email) {
        return EMAIL_PATTERN.matcher(email).matches();
    }
}
",1,PERPLEXITY,Write a Java method with regex pattern to validate email addresses comprehensively,JAVA

,"class Solution {
    public List<Integer> findAnagrams(String s, String p) {
        ArrayList<Integer> ans= new ArrayList<>();
        int pfreq []=new int [256];
        int sfreq []=new int [256];
        int low=0;
        int len=0;
        for(int i=0;i<p.length(); i++){
            pfreq[p.charAt(i)]++;
        }
        for(int high=0; high<s.length(); high++){
               sfreq[s.charAt(high)]++;
               len=high-low+1;
            
               while(len>p.length()){
                    sfreq[s.charAt(low)]--;
                    low++;
                    len = high - low + 1;
                   
               }
                     if(isAnagram(sfreq,pfreq)){
                    ans.add(low);
                  }
        }
        return ans;
    }

    public boolean isAnagram(int []sfreq, int [] pfreq){
        for(int i=0;i<256; i++ ){
            if(pfreq[i]!=sfreq[i]){
                return false;
            }
        }
        return true;
    }
}",0,leetcode,NA,JAVA

,"import java.util.List;
import java.nio.file.Files;
import java.nio.file.Paths;
public class FileReaderUtil {
    public static List<String> readFile(String path) throws Exception {
        try (var lines = Files.newBufferedReader(Paths.get(path))) {
            return Files.readAllLines(Paths.get(path));
        }
    }
}
",1,PERPLEXITY,"Create a Java method to read all lines from a file using try-with-resources and return as List.""",JAVA

,"import java.util.*;

class AllOne {

    // Bucket node for doubly linked list
    private static class Bucket {
        int count;
        Set<String> keys;
        Bucket prev, next;

        Bucket(int count) {
            this.count = count;
            this.keys = new HashSet<>();
        }
    }

    private Bucket head, tail;
    private Map<String, Bucket> keyToBucket;

    public AllOne() {
        head = new Bucket(0);   // dummy head
        tail = new Bucket(0);   // dummy tail
        head.next = tail;
        tail.prev = head;
        keyToBucket = new HashMap<>();
    }

    public void inc(String key) {
        if (!keyToBucket.containsKey(key)) {
            // insert new key with count = 1
            Bucket first = head.next;
            if (first != tail && first.count == 1) {
                first.keys.add(key);
                keyToBucket.put(key, first);
            } else {
                Bucket newBucket = new Bucket(1);
                newBucket.keys.add(key);
                insertAfter(head, newBucket);
                keyToBucket.put(key, newBucket);
            }
        } else {
            Bucket curr = keyToBucket.get(key);
            Bucket next = curr.next;

            if (next != tail && next.count == curr.count + 1) {
                next.keys.add(key);
                keyToBucket.put(key, next);
            } else {
                Bucket newBucket = new Bucket(curr.count + 1);
                newBucket.keys.add(key);
                insertAfter(curr, newBucket);
                keyToBucket.put(key, newBucket);
            }

            curr.keys.remove(key);
            if (curr.keys.isEmpty()) {
                remove(curr);
            }
        }
    }

    public void dec(String key) {
        Bucket curr = keyToBucket.get(key);

        if (curr.count == 1) {
            // remove key completely
            curr.keys.remove(key);
            keyToBucket.remove(key);
            if (curr.keys.isEmpty()) {
                remove(curr);
            }
        } else {
            Bucket prev = curr.prev;

            if (prev != head && prev.count == curr.count - 1) {
                prev.keys.add(key);
                keyToBucket.put(key, prev);
            } else {
                Bucket newBucket = new Bucket(curr.count - 1);
                newBucket.keys.add(key);
                insertAfter(curr.prev, newBucket);
                keyToBucket.put(key, newBucket);
            }

            curr.keys.remove(key);
            if (curr.keys.isEmpty()) {
                remove(curr);
            }
        }
    }

    public String getMaxKey() {
        if (tail.prev == head) return """";
        return tail.prev.keys.iterator().next();
    }

    public String getMinKey() {
        if (head.next == tail) return """";
        return head.next.keys.iterator().next();
    }

    // Doubly linked list helpers
    private void insertAfter(Bucket prev, Bucket node) {
        node.prev = prev;
        node.next = prev.next;
        prev.next.prev = node;
        prev.next = node;
    }

    private void remove(Bucket node) {
        node.prev.next = node.next;
        node.next.prev = node.prev;
    }
}


/**
 * Your AllOne object will be instantiated and called as such:
 * AllOne obj = new AllOne();
 * obj.inc(key);
 * obj.dec(key);
 * String param_3 = obj.getMaxKey();
 * String param_4 = obj.getMinKey();
 */",0,leetcode,NA,JAVA

,"import java.util.UUID;
public class UUIDUtil {
    public static String generate() {
        return UUID.randomUUID().toString();
    }
    public static boolean isValid(String uuid) {
        try {
            UUID.fromString(uuid);
            return true;
        } catch (IllegalArgumentException e) {
            return false;
        }
    }
}
",1,PERPLEXITY,Implement a Java utility to generate UUID v4 strings and validate their format,JAVA

,"class Solution {
    public String originalDigits(String s) {
        int[] charCount = new int[26];
        for (char c : s.toCharArray()) {
            charCount[c - 'a']++;
        }
        
        int[] digitCount = new int[10];
        
        digitCount[0] = charCount['z' - 'a'];
        digitCount[2] = charCount['w' - 'a'];
        digitCount[4] = charCount['u' - 'a'];
        digitCount[6] = charCount['x' - 'a'];
        digitCount[8] = charCount['g' - 'a'];
        
        digitCount[3] = charCount['h' - 'a'] - digitCount[8];
        digitCount[5] = charCount['f' - 'a'] - digitCount[4];
        digitCount[7] = charCount['s' - 'a'] - digitCount[6];
        
        digitCount[1] = charCount['o' - 'a'] - digitCount[0] - digitCount[2] - digitCount[4];
        digitCount[9] = charCount['i' - 'a'] - digitCount[5] - digitCount[6] - digitCount[8];
        
        StringBuilder result = new StringBuilder();
        for (int i = 0; i < 10; i++) {
            for (int j = 0; j < digitCount[i]; j++) {
                result.append(i);
            }
        }
        
        return result.toString();
    }
}",0,leetcode,NA,JAVA

,"import java.util.*;

class Solution {
    public int openLock(String[] deadends, String target) {
        Set<String> deadendSet = new HashSet<>(Arrays.asList(deadends));
        if (deadendSet.contains(""0000"")) {
            return -1;
        }
        
        Queue<Pair<String, Integer>> queue = new LinkedList<>();
        queue.offer(new Pair<>(""0000"", 0));
        Set<String> visited = new HashSet<>();
        visited.add(""0000"");
        
        while (!queue.isEmpty()) {
            Pair<String, Integer> current = queue.poll();
            String currentCombination = current.getKey();
            int moves = current.getValue();
            
            if (currentCombination.equals(target)) {
                return moves;
            }
            
            for (int i = 0; i < 4; i++) {
                for (int delta : new int[]{-1, 1}) {
                    int newDigit = (currentCombination.charAt(i) - '0' + delta + 10) % 10;
                    String newCombination = currentCombination.substring(0, i) +
                                             newDigit +
                                             currentCombination.substring(i + 1);
                    
                    if (!visited.contains(newCombination) && !deadendSet.contains(newCombination)) {
                        visited.add(newCombination);
                        queue.offer(new Pair<>(newCombination, moves + 1));
                    }
                }
            }
        }
        
        return -1; // Target is not reachable
    }
}",0,leetcode,NA,JAVA

,"class Solution {
    public int longestPalindrome(String s) {
        HashMap<Character, Integer> hm = new HashMap<Character, Integer>();
       
        int cnt=0;
        Boolean odd=false;
        for(char ch : s.toCharArray())
        hm.put(ch, hm.getOrDefault(ch,0)+1 );
        for(int i : hm.values())
        {
            if(i%2==0)
            cnt+=i;
            else
            {
                cnt+=i-1;
                odd =true;
            }
        }
        if(odd)
        return ++cnt;
        else
        return cnt;
    }
}class Solution {
    public int longestPalindrome(String s) {
        HashMap<Character, Integer> hm = new HashMap<Character, Integer>();
       
        int cnt=0;
        Boolean odd=false;
        for(char ch : s.toCharArray())
        hm.put(ch, hm.getOrDefault(ch,0)+1 );
        for(int i : hm.values())
        {
            if(i%2==0)
            cnt+=i;
            else
            {
                cnt+=i-1;
                odd =true;
            }
        }
        if(odd)
        return ++cnt;
        else
        return cnt;
    }
}",0,leetcode,NA,JAVA

,"class Solution {
    public int fourSumCount(int[] nums1, int[] nums2, int[] nums3, int[] nums4) {
        HashMap<Integer,Integer> map =new HashMap<>();
        int count=0;
        for(int a:nums1)
        {
            for(int b:nums2)
            {
                int sum=a+b;
                map.put(sum,map.getOrDefault(sum,0)+1);
            }
        }
        for(int c : nums3)
        {
            for(int d:nums4)
            {
                int sum=c+d;
                if(map.containsKey(-sum))
                {
                    count +=  map.get(-sum);
                }
            }
        }
        return count;
    }
}",0,leetcode,NA,JAVA

,"class Solution {
    public boolean isRectangleCover(int[][] rectangles) {
        TreeSet<int[]> set = new TreeSet<int[]>((a, b) -> {
            if (a[3] <= b[1]) return -1;
            else if (a[1] >= b[3]) return 1;
            else if (a[2] <= b[0]) return -1;
            else if (a[0] >= b[2]) return 1;
            else return 0;
        });
        int minX = Integer.MAX_VALUE, minY = Integer.MAX_VALUE;
        int maxA = Integer.MIN_VALUE, maxB = Integer.MIN_VALUE;
        int totalArea = 0;
        for (int[] i : rectangles) {
            if (i[0] < minX) {
                minX = i[0];
            } if (i[1] < minY) {
                minY = i[1];
            } if (i[2] > maxA) {
                maxA = i[2];
            } if (i[3] > maxB) {
                maxB = i[3];
            }
            totalArea += (i[2] - i[0]) * (i[3] - i[1]);
            if (!set.add(i)) return false;
        }
        return totalArea == (maxA - minX) * (maxB - minY);
    }
}",0,leetcode,NA,JAVA

,"public enum Singleton {
    INSTANCE;
    private Singleton() {}
    public void doSomething() {
        System.out.println(""Singleton instance method"");
    }
    public static Singleton getInstance() {
        return INSTANCE;
    }
}
",1,PERPLEXITY,Write a thread-safe singleton class in Java using enum pattern,JAVA

,"class Solution {
    public boolean canConstruct(String ransomNote, String magazine) {
                if (ransomNote.length() > magazine.length()) return false;
        int[] alphabets_counter = new int[26];
        
        for (char c : magazine.toCharArray())
            alphabets_counter[c-'a']++;

        for (char c : ransomNote.toCharArray()){
            if (alphabets_counter[c-'a'] == 0) return false;
            alphabets_counter[c-'a']--;
        }
        return true;
    }
}",0,leetcode,NA,JAVA

,"interface Shape { void draw(); }
class Circle implements Shape {
    public void draw() { System.out.println(""Drawing Circle""); }
}
class Rectangle implements Shape {
    public void draw() { System.out.println(""Drawing Rectangle""); }
}
public class ShapeFactory {
    public static Shape createShape(String type) {
        switch (type.toLowerCase()) {
            case ""circle"": return new Circle();
            case ""rectangle"": return new Rectangle();
            default: throw new IllegalArgumentException(""Unknown shape"");
        }
    }
}
",1,PERPLEXITY,Create a Java factory method pattern to create different Shape objects based on string input,JAVA

,"class Solution {
    public int findLUSlength(String[] strs) {
        int n = strs.length;
        int len = -1;
        HashSet<String> set = new HashSet<>();
        for(int i =0;i<n;i++){
            String str = strs[i];

            if(!set.contains(str)){
                boolean possibilities = true;
                for(int j=0;j<n;j++)
                {
                    if(i == j) continue;
                    String temp = strs[j];
                    if(str.equals(temp)) {
                        set.add(str);
                        set.add(temp);
                        possibilities = false;
                        break;
                    }
                    int len1 = str.length();
                    int len2 = temp.length();
                    int p =0;int q=0;
                    while(p < len1 && q < len2){
                        if(str.charAt(p) == temp.charAt(q)){
                            p++;
                            q++;
                        }else q++;
                    }
                    if(p == len1) possibilities = false;
                }
                if(possibilities) len = Math.max(len, str.length());
            }
        }

        return len;
    }
}",0,leetcode,NA,JAVA

,"public class Solution {
    public int findLHS(int[] nums) {
        Arrays.sort(nums);
        int j = 0;
        int maxLength = 0;
        
        for (int i = 0; i < nums.length; i++) {
            while (nums[i] - nums[j] > 1) {
                j++;
            }
            if (nums[i] - nums[j] == 1) {
                maxLength = Math.max(maxLength, i - j + 1);
            }
        }
        return maxLength;
    }
}",0,leetcode,NA,JAVA

,"class Solution {
    int i=0,j=0;
     int m=0;int n=0;

    public Solution(int m, int n) {
        this.m=m;
        this.n=n;
    }
    
    public int[] flip() {
        j++;
        if(j==n){
            j=0;
            i++;
        }
        if(i==m){
            i=0;
            j=0;
        }

             
        return new int[]{i,j};
        
    }
    
    public void reset() {
      
        
        
        
    }
}

/**
 * Your Solution object will be instantiated and called as such:
 * Solution obj = new Solution(m, n);
 * int[] param_1 = obj.flip();
 * obj.reset();
 */",0,leetcode,NA,JAVA

,"class WordFilter {
    constructor(words) {
        this.pTrie = new Array(27)
        this.sTrie = new Array(27)
        let wordSet = new Set()
        for (let index = words.length - 1; ~index; index--) {
            let word = words[index], wlen = word.length
            if (wordSet.has(word))
                continue;
            wordSet.add(word)
            this.insert(word, index, this.pTrie, 0, wlen, 1)
            this.insert(word, index, this.sTrie, wlen-1, -1, -1)
        }
    }
    
    insert(word, index, trie, start, end, step) {
        for (let i = start; i != end; i += step) {
            let c = word.charCodeAt(i) - 97
            if (!trie[c]) trie[c] = new Array(27)
            trie = trie[c]
            if (!trie[26]) trie[26] = []
            trie[26].push(index)
        }
    }
    
    retrieve(word, trie, start, end, step) {
        for (let i = start; i != end; i += step) {
            let c = word.charCodeAt(i) - 97
            if (!trie[c]) return []
            trie = trie[c]
        }
        return trie[26]
    }
    
    f(pre, suf) {
        let pVals = this.retrieve(pre, this.pTrie, 0, pre.length, 1),
            sVals = this.retrieve(suf, this.sTrie, suf.length-1, -1, -1),
            svix = 0, pvix = 0
        while (svix < sVals.length && pvix < pVals.length) {
            let sVal = sVals[svix], pVal = pVals[pvix]
            if (sVal === pVal) return sVal
            sVal > pVal ? svix++ : pvix++
        }
        return -1
    }
};",0,leetcode,NA,JAVA

,"class Solution {
    int maxF=0;
    List<Integer> maxSumArr = new ArrayList<>();
    Map<Integer, Integer> f = new HashMap<>();

    public int[] findFrequentTreeSum(TreeNode root) {
        solve(root);

        int[] arr = new int[maxSumArr.size()];
        for(int i=0; i<arr.length; i++){
            arr[i] = maxSumArr.get(i);
        }
        return arr;
    }

    public int solve(TreeNode root){
        if(root == null) return 0;
        
        int sum = root.val + solve(root.left) + solve(root.right);
        f.put(sum , f.getOrDefault(sum, 0) + 1);
        
        if(f.get(sum) > maxF){
            maxSumArr.clear();
            maxSumArr.add(sum);
            maxF = f.get(sum);
        }else if(f.get(sum) == maxF){
            maxSumArr.add(sum);
        }

        return sum;
    }
}",0,leetcode,NA,JAVA

,"import java.util.ArrayList;
import java.util.List;
public class Subject {
    private List<Observer> observers = new ArrayList<>();
    private int state;
    public int getState() { return state; }
    public void setState(int state) {
        this.state = state;
        notifyObservers();
    }
    public void attach(Observer observer) { observers.add(observer); }
    public void notifyObservers() {
        for (Observer o : observers) o.update();
    }
}
interface Observer { void update(); }
",1,PERPLEXITY,Implement observer pattern in Java with Subject and Observer interfaces,JAVA

,"class Solution {
    public String[] findWords(String[] words) {
       ArrayList<String> ans=new ArrayList<>();
       String first = ""qwertyuiop"";
       String Secound =""asdfghjkl"";
       String Third=""zxcvbnm"";
       for(String i : words){
        if(isinrow(i,first) || isinrow(i,Secound) || isinrow(i,Third))
         ans.add(i);
       } 
       return ans.toArray(new String[0]);
    }
    private boolean isinrow(String s,String row){
      for(char c:s.toCharArray()){
        if(row.indexOf(Character.toLowerCase(c))==-1){
            return false;
        }
      }
      return true;
    }
}",0,leetcode,NA,JAVA

,"public int deleteAndEarn(int[] nums) {
        var numToCount = new HashMap<Integer, Integer>();
        var min = Integer.MAX_VALUE;
        var max = Integer.MIN_VALUE;
        for (var num : nums) {
                numToCount.compute(num, (k, v) -> v == null ? 1 : ++v);
                min = Math.min(min, num);
                max = Math.max(max, num);
        }

        var prevIncEarn = 0;
        var prevExcEarn = 0;
        for (var i = min; i <= max; i++) {
                var incEarn = prevExcEarn + i * numToCount.getOrDefault(i, 0);
                var excEarn = Math.max(prevIncEarn, prevExcEarn);
                prevIncEarn = incEarn;
                prevExcEarn = excEarn;
        }
        return Math.max(prevIncEarn, prevExcEarn);
}",0,leetcode,NA,JAVA

,"class Solution {
    public int[] nextGreaterElement(int[] nums1, int[] nums2) {
        int[] ans = new int[nums1.length];
        Arrays.fill(ans, -1);
        int index = 0;
        for(int i=0; i<nums1.length; i++){
            for(int j=0; j<nums2.length; j++){
                if(nums1[i] == nums2[j]){
                    for(int k=j; k<nums2.length; k++){
                        if(nums2[k] > nums2[j]){
                            ans[i] = nums2[k];
                            break;

                        }
                    }
                }
            }
        }
        return ans;
        
    }
}",0,leetcode,NA,JAVA

,"class Solution {
    public String findReplaceString(String s, int[] indices, String[] sources, String[] targets) {
        Map<Integer,Integer> map=new HashMap<>();
        for (int i=0; i<indices.length; i++){
            if (s.startsWith(sources[i],indices[i])){
                map.put(indices[i],i);
            }
        }  
        StringBuilder sb=new StringBuilder();
        for (int i=0; i<s.length();){
            if (!map.containsKey(i)){
                sb.append(s.charAt(i));
                i++;
            } else { //replace chars
                sb.append(targets[map.get(i)]); 
                i+=sources[map.get(i)].length();
            }
        }
        return sb.toString();
    }
}",0,leetcode,NA,JAVA

,"class Solution {
    int[] arr;
    HashSet<List<Integer>> hashSet = new HashSet<>();
    public List<List<Integer>> findSubsequences(int[] nums) {
        arr = nums;
        List<Integer> arrayList = new ArrayList<>();
        recursion(arrayList,0);
        List<List<Integer>> result = new ArrayList<>(hashSet);
        return result;
    }

    public void recursion(List<Integer> arrayList, int index){
        if(arrayList.size()>=2) hashSet.add(new ArrayList(arrayList));

        for(int i = index;i<arr.length;i++){
            if(arrayList.size() == 0 || arr[i]>= arrayList.get(arrayList.size()-1)){
                arrayList.add(arr[i]);
                recursion(arrayList,i+1);
                arrayList.remove(arrayList.size()-1);
            }
        }

    }
}",0,leetcode,NA,JAVA

,"interface SortStrategy { void sort(int[] arr); }
class BubbleSortStrategy implements SortStrategy {
    public void sort(int[] arr) {
        for (int i = 0; i < arr.length - 1; i++) {
            for (int j = 0; j < arr.length - i - 1; j++) {
                if (arr[j] > arr[j + 1]) {
                    int temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp;
                }
            }
        }
    }
}
public class Sorter {
    private SortStrategy strategy;
    public void setStrategy(SortStrategy strategy) { this.strategy = strategy; }
    public void sort(int[] arr) { strategy.sort(arr); }
}
",1,PERPLEXITY,Create strategy pattern in Java for different sorting algorithms.,JAVA

,"class Solution {
    public double[] medianSlidingWindow(int[] nums, int k) {
        if (nums == null || nums.length == 0)
            return new double[0];
        
        Node root = null;
        for (int i = 0; i < k; i++) {
            root = insert(root, nums[i]);
        }
        
        double[] r = new double[nums.length - k + 1];
        boolean even = k % 2 == 0;
        int j = 0;
        for (int i = k; i <= nums.length; i++) {
            double sum = 0.0;
            if (even)
                sum = (findSmallest(root, k/2).val + findSmallest(root, k/2 + 1).val) / 2.0;
            else
                sum = findSmallest(root, k/2 + 1).val;
            r[j++] = sum;
            if (i < nums.length) {
                root = insert(root, nums[i]);
                root = delete(root, nums[i - k]);
            }
        }
        
        return r;
    }
    
    private Node findSmallest(Node root, int k) {
        int s = countWith(root.left) + 1;
        if (s == k)
            return root;
        if (s > k) {
            return findSmallest(root.left, k);
        }
        return findSmallest(root.right, k - s);
    } 
  
    private Node delete(Node root, long val) {
        if (root == null)
            return null;
        else if (val > root.val) 
            root.right = delete(root.right, val);
        else if (val < root.val)
            root.left = delete(root.left, val);
        else {
            if (root.left == null)
                root = root.right;
            else if (root.right == null)
                root = root.left;
            else {
                Node t = findMin(root.right);
                root.val = t.val;
                root.right = delete(root.right, t.val);
            }
        }
        
        return updateNode(root);
    }
    
    private Node findMin(Node root) {
        if (root.left != null)
            return findMin(root.left);
        return root;
    }

    private Node insert(Node root, long val)
    {
        if (root == null)
        {
            return new Node(val);
        }
        if (val >= root.val)
        {
            root.right = insert(root.right, val);
        }
        else
        {
            root.left = insert(root.left, val);
        }
       
        return updateNode(root);
    }
    
    private Node updateNode(Node root) {
        int b = balance(root);                 
        if (b == 2 && balance(root.left) < 0)
        {
            root.left = leftRotate(root.left);
            root = rightRotate(root);
        }
        else if (b == -2 && balance(root.right) > 0)
        {
            root.right = rightRotate(root.right);
            root = leftRotate(root);
        }
        else if (b == 2)
        {
            root = rightRotate(root);
        }
        else if (b == -2)
        {
            root = leftRotate(root);
        }
        update(root);
        return root;
    }

    private Node leftRotate(Node n)
    {
        Node r = n.right;
        n.right = r.left;
        r.left = n;
        update(n);
        update(r);
        return r;
    }

    private Node rightRotate(Node n)
    {
        Node l = n.left;
        n.left = l.right;
        l.right = n;
        update(n);
        update(l);
        return l;
    }

    private int balance(Node n)
    {
        if (n==null)return 0;
        return height(n.left) - height(n.right);
    }

    private void update(Node n)
    {
        if (n==null)return;
        n.height = Math.max(height(n.left), height(n.right)) + 1;
        n.count = n.left != null ? n.left.count + 1 : 0;
        n.count += n.right != null ? n.right.count + 1 : 0;
    }

    private int height(Node n)
    {
        return n != null ? n.height : 0;
    }

    private int countWith(Node n)
    {
        return n != null ? n.count + 1 : 0;
    }

    static class Node
    {
        Node left;
        Node right;
        long val;
        int count;
        int height;

        Node(long val)
        {
            this.val = val;
        }
    }
}",0,leetcode,NA,JAVA

,"public class User {
    private String name, email, phone;
    private int age;
    private User(Builder builder) {
        this.name = builder.name;
        this.email = builder.email;
        this.phone = builder.phone;
        this.age = builder.age;
    }
    public static class Builder {
        private String name, email, phone;
        private int age;
        public Builder name(String name) { this.name = name; return this; }
        public Builder email(String email) { this.email = email; return this; }
        public Builder phone(String phone) { this.phone = phone; return this; }
        public Builder age(int age) { this.age = age; return this; }
        public User build() { return new User(this); }
    }
}
",1,PERPLEXITY,Write Java builder pattern for a complex User object with multiple optional fields,JAVA

,"class LFUCache {
  public LFUCache(int capacity) {
    this.capacity = capacity;
  }

  public int get(int key) {
    if (!keyToVal.containsKey(key))
      return -1;

    final int freq = keyToFreq.get(key);
    freqToLRUKeys.get(freq).remove(key);
    if (freq == minFreq && freqToLRUKeys.get(freq).isEmpty()) {
      freqToLRUKeys.remove(freq);
      ++minFreq;
    }

    // Increase key's freq by 1
    // Add this key to next freq's list
    putFreq(key, freq + 1);
    return keyToVal.get(key);
  }

  public void put(int key, int value) {
    if (capacity == 0)
      return;
    if (keyToVal.containsKey(key)) {
      keyToVal.put(key, value);
      get(key); // Update key's count
      return;
    }

    if (keyToVal.size() == capacity) {
      // Evict LRU key from the minFreq list
      final int keyToEvict = freqToLRUKeys.get(minFreq).iterator().next();
      freqToLRUKeys.get(minFreq).remove(keyToEvict);
      keyToVal.remove(keyToEvict);
    }

    minFreq = 1;
    putFreq(key, minFreq);    // Add new key and freq
    keyToVal.put(key, value); // Add new key and value
  }

  private int capacity;
  private int minFreq = 0;
  private Map<Integer, Integer> keyToVal = new HashMap<>();
  private Map<Integer, Integer> keyToFreq = new HashMap<>();
  private Map<Integer, LinkedHashSet<Integer>> freqToLRUKeys = new HashMap<>();

  private void putFreq(int key, int freq) {
    keyToFreq.put(key, freq);
    freqToLRUKeys.putIfAbsent(freq, new LinkedHashSet<>());
    freqToLRUKeys.get(freq).add(key);
  }
}",0,leetcode,NA,JAVA
,"class Solution {
    public boolean circularArrayLoop(int[] nums) {
        int n = nums.length;

        for (int i = 0; i < n; i++) {
            int slow = i, fast = i;
            boolean forward = nums[i] > 0;

            while (true) {
                slow = next(nums, slow);
                if ((nums[slow] > 0) != forward) break;

                fast = next(nums, fast);
                if ((nums[fast] > 0) != forward) break;

               fast = next(nums, fast); 
                if ((nums[fast] > 0) != forward) break;

                if (slow == fast) {
                    if (slow == next(nums, slow)) break;
                    return true;
                }
            }
        }
        return false;
    }

    private int next(int[] nums, int i) {
        int n = nums.length;
        int next = (i + nums[i]) % n;
        if (next < 0) next += n;
        return next;
    }
}",0,leetcode,NA,JAVA
,"class Solution {
    public int numFactoredBinaryTrees(int[] arr) {
        Arrays.sort(arr);
        Map<Integer, Long> subtreeCount = new HashMap<>();

        for (int root : arr) {
            subtreeCount.put(root, 1L);

            for (int factor : arr) {
                if (factor >= root) {
                    break;
                }

                if (root % factor == 0 && subtreeCount.containsKey(root / factor)) {
                    subtreeCount.put(root, (subtreeCount.get(root) + subtreeCount.get(factor) * subtreeCount.get(root / factor)));
                }
            }
        }

        long totalTrees = 0L;
        for (int key : subtreeCount.keySet()) {
            totalTrees = (totalTrees + subtreeCount.get(key)) % 1_000_000_007;
        }

        return (int) totalTrees;       
    }
}",0,leetcode,NA,JAVA
,"// 6 ms. 98.66%
public int distributeCandies(int[] candyType) {
    BitSet bits = new BitSet(200001);
    int count = 0, max = candyType.length / 2;
    for(int candy: candyType) {
        int t = candy + 100000;
        if(!bits.get(t)) {
            if(++count == max) return max;
            bits.set(t);
        }
    }
    return count;
}",0,leetcode,NA,JAVA
,"public int flipgame(int[] f, int[] b) {
        HashSet<Integer> same = new HashSet<>();
        for (int i = 0; i < f.length; ++i)
            if (f[i] == b[i])
                same.add(f[i]);
        int res = 3000;
        for (int i : f)
            if (!same.contains(i))
                res = Math.min(res, i);
        for (int i : b)
            if (!same.contains(i))
                res = Math.min(res, i);
        return res % 3000;
    }",0,leetcode,NA,JAVA
,"class Solution {
    public boolean checkInclusion(String s1, String s2) {
        if (s1.length() > s2.length()) {
            return false;
        }
        
        HashMap<Character, Integer> s1Count = new HashMap<>();
        HashMap<Character, Integer> s2Count = new HashMap<>();
        
        for (int i = 0; i < s1.length(); i++) {
            s1Count.put(s1.charAt(i), s1Count.getOrDefault(s1.charAt(i), 0) + 1);
            s2Count.put(s2.charAt(i), s2Count.getOrDefault(s2.charAt(i), 0) + 1);
        }
        
        if (s1Count.equals(s2Count)) {
            return true;
        }
        
        int left = 0;
        for (int right = s1.length(); right < s2.length(); right++) {
            char charRight = s2.charAt(right);
            s2Count.put(charRight, s2Count.getOrDefault(charRight, 0) + 1);
            
            char charLeft = s2.charAt(left);
            s2Count.put(charLeft, s2Count.get(charLeft) - 1);
            if (s2Count.get(charLeft) == 0) {
                s2Count.remove(charLeft);
            }
            
            left++;
            
            if (s1Count.equals(s2Count)) {
                return true;
            }
        }
        
        return false;        
    }
}",0,leetcode,NA,JAVA
,"public class NumberPrinter implements Runnable {
    private int id;
    public NumberPrinter(int id) { this.id = id; }
    @Override
    public void run() {
        for (int i = 1; i <= 10; i++) {
            System.out.println(""Thread "" + id + "": "" + i);
            try { Thread.sleep(100); } catch (InterruptedException e) {}
        }
    }
}
",1,PERPLEXITY,Create a Java Thread class that implements Runnable to print numbers from 1 to 10,JAVA
,"class Solution {
    public int subarraySum(int[] nums, int k) {
        HashMap<Integer, Integer> subNum = new HashMap<>();
        subNum.put(0, 1);
        int total = 0, count = 0;

        for (int n : nums) {
            total += n;

            if (subNum.containsKey(total - k)) {
                count += subNum.get(total - k);
            }

            subNum.put(total, subNum.getOrDefault(total, 0) + 1);
        }

        return count;        
    }
}",0,leetcode,NA,JAVA
,"class TrieNode {
    TrieNode[] branch = new TrieNode[26];
    Boolean isEmpty = true;
}

class Solution {
    public int minimumLengthEncoding(String[] W) {
        TrieNode trie = new TrieNode();
        trie.branch = new TrieNode[26];
        int ans = 1;
        for (String word : W) {
            TrieNode curr = trie;
            Boolean newWord = false;
            for (int i = word.length() - 1; i >= 0; i--) {
                int c = word.charAt(i) - 'a';
                if (curr.isEmpty && !newWord) ans -= word.length() - i;
                if (curr.branch[c] == null) {
                    curr.branch[c] = new TrieNode();
                    newWord = true;
                    curr.isEmpty = false;
                }
                curr = curr.branch[c];
            }
            if (newWord) ans += word.length() + 1;
        }
        return ans;
    }
}",0,leetcode,NA,JAVA
,"class Solution {
    public int leastBricks(List<List<Integer>> wall) 
    {
        HashMap<Integer, Integer> edge_frequency = new HashMap<>(); // HashMap to store the number of common edges among the rows
        int max_frequency = 0; // Variable to store the frequency of most occuring edge
        
        for(int row=0; row<wall.size(); row++) // Iterating through each row
        {
            int edge_postion = 0; // Variable to store different edge postion
            
            for(int brick_no=0; brick_no<wall.get(row).size()-1; brick_no++) // Iterating through each brick inside a row
            {
                int current_brick_length = wall.get(row).get(brick_no); // Length of the current brick
                edge_postion = edge_postion + current_brick_length; // Next Edge Position = Previous Edge Position + Current Brick's Length
                edge_frequency.put(edge_postion,edge_frequency.getOrDefault(edge_postion,0)+1); // Incrementing the Frequency of just calculated Edge Postion
                max_frequency = Math.max(edge_frequency.get(edge_postion), max_frequency); // Comparing the ""Frequency of just calculated Edge Postion"" with ""Max Frequency seen till now"" & storing whichever is greater.
            }
        }
        return wall.size() - max_frequency; // returning (Number of Bricks Crossed by Line) i.e. (Number of Rows in Wall - Frequency of Most Occuring Edge)
    }
}",0,leetcode,NA,JAVA

,"import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ThreadPoolExample {
    public static void main(String[] args) {
        ExecutorService executor = Executors.newFixedThreadPool(3);
        for (int i = 1; i <= 5; i++) {
            int taskId = i;
            executor.submit(() -> {
                System.out.println(""Task "" + taskId + "" executed by "" + 
                    Thread.currentThread().getName());
            });
        }
        executor.shutdown();
    }
}
",1,PERPLEXITY,Write Java code using ExecutorService to execute 5 tasks in a thread pool.,JAVA

,"public class Codec {
    Map<String, String> codeDB = new HashMap<>(), urlDB = new HashMap<>();
    static final String chars = ""0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"";

    private String getCode() {
        char[] code = new char[6];
        for (int i = 0; i < 6; i++) 
            code[i] = chars.charAt((int)(Math.random() * 62));
        return ""http://tinyurl.com/"" + String.valueOf(code);
    }
    
    public String encode(String longUrl) {
        if (urlDB.containsKey(longUrl)) return urlDB.get(longUrl);
        String code = getCode();
        while (codeDB.containsKey(code)) code = getCode();
        codeDB.put(code, longUrl);
        urlDB.put(longUrl, code);
        return code;
    }

    public String decode(String shortUrl) {
        return codeDB.get(shortUrl);
    }
}",0,leetcode,NA,JAVA

,"class Solution {
    public int numComponents(ListNode head, int[] nums) {
    Set<Integer> set = new HashSet<>();
    for (int x : nums) set.add(x);

    ListNode curr = head;
    int count = 0;
    while (curr != null) {
        // If current node is in set and (it's the last node OR next node is not in set)
        if (set.contains(curr.val) && (curr.next == null || !set.contains(curr.next.val))) {
            count++;
        }
        curr = curr.next;
    }
    return count;
}

}",0,leetcode,NA,JAVA
,"// O(n) Time Solution

 class Solution {
                 public int findPairs(int[] nums, int k) {
                         Map<Integer, Integer> map = new HashMap();
                         for (int num : nums)
                                 map.put(num, map.getOrDefault(num, 0) + 1);

                         int result = 0;
                         for (int i : map.keySet())
                                 if (k > 0 && map.containsKey(i + k) || k == 0 && map.get(i) > 1)
                                         result++;
                         return result;
                 }
         }",0,leetcode,NA,JAVA
,"import java.util.concurrent.CompletableFuture;
public class CompletableFutureExample {
    public static CompletableFuture<String> processAsync(int input) {
        return CompletableFuture.supplyAsync(() -> {
            try { Thread.sleep(1000); } catch (Exception e) {}
            return ""Processed: "" + input;
        }).thenApply(result -> result.toUpperCase());
    }
}
",1,PERPLEXITY,Create a Java CompletableFuture example that chains two asynchronous operations,JAVA
,"class Solution {
    public int findMaxLength(int[] nums) {
        // Map to store first occurrence of diff
        HashMap<Integer, Integer> map = new HashMap<>();
        
        int zero = 0, one = 0;
        int res = 0;

        for (int i = 0; i < nums.length; i++) {

            if (nums[i] == 0)
                zero++;
            else
                one++;

            int diff = zero - one;

            // If diff == 0, subarray from 0 to i is valid
            if (diff == 0) {
                res = Math.max(res, i + 1);
            }

            // If diff not seen before, store index
            if (!map.containsKey(diff)) {
                map.put(diff, i);
            } 
            // If seen before, calculate length
            else {
                int idx = map.get(diff);
                int len = i - idx;
                res = Math.max(res, len);
            }
        }

        return res;
    }
}",0,leetcode,NA,JAVA
,"import java.util.concurrent.Semaphore;
public class SemaphoreExample {
    private static Semaphore semaphore = new Semaphore(3);
    public static void accessResource(int id) {
        try {
            semaphore.acquire();
            System.out.println(""Resource accessed by "" + id);
            Thread.sleep(2000);
        } catch (InterruptedException e) {} 
        finally { semaphore.release(); }
    }
}
",1,PERPLEXITY,Implement a semaphore in Java to limit concurrent access to 3 resources,JAVA
,"class Solution {
    public boolean checkSubarraySum(int[] nums, int k) {      
        // maintain a hash map to store <sum % k, index>
        Map<Integer, Integer> map = new HashMap<>();
        int sum = 0;
        for (int i = 0; i < nums.length; i++) {
            sum += nums[i];
            sum %= k; 
            // case 1
            if (sum == 0 && i > 0) {
                return true;
            }
            // case 2
            if (map.containsKey(sum) && i - map.get(sum) > 1) { 
                return true;
            }
            if (!map.containsKey(sum)) {
                map.put(sum, i); 
            }
            
        }
        return false;
    }
}",0,leetcode,NA,JAVA
,"class Solution {
    public int numBusesToDestination(int[][] routes, int source, int target) {
        if (source == target) {
            return 0;
        }
        int maxStop = -1;
        for (int[] route : routes) {
            for (int stop : route) {
                maxStop = Math.max(maxStop, stop);
            }
        }
        if (maxStop < target) {
            return -1;
        }
        int n = routes.length;
        int[] minBusesToReach = new int[maxStop + 1];
        Arrays.fill(minBusesToReach, n + 1);
        minBusesToReach[source] = 0;
        boolean flag = true;
        while (flag) {
            flag = false;
            for (int[] route : routes) {
                int min = n + 1;
                for (int stop : route) {
                    min = Math.min(min, minBusesToReach[stop]);
                }
                min++;
                for (int stop : route) {
                    if (minBusesToReach[stop] > min) {
                        minBusesToReach[stop] = min;
                        flag = true;
                    }
                }
            }
            
        }
        return (minBusesToReach[target] < n + 1 ? minBusesToReach[target] : -1);
    }
}",0,leetcode,NA,JAVA
,"class Solution {
    public int findLUSlength(String[] strs) {
        int n = strs.length;
        int len = -1;
        HashSet<String> set = new HashSet<>();
        for(int i =0;i<n;i++){
            String str = strs[i];

            if(!set.contains(str)){
                boolean possibilities = true;
                for(int j=0;j<n;j++)
                {
                    if(i == j) continue;
                    String temp = strs[j];
                    if(str.equals(temp)) {
                        set.add(str);
                        set.add(temp);
                        possibilities = false;
                        break;
                    }
                    int len1 = str.length();
                    int len2 = temp.length();
                    int p =0;int q=0;
                    while(p < len1 && q < len2){
                        if(str.charAt(p) == temp.charAt(q)){
                            p++;
                            q++;
                        }else q++;
                    }
                    if(p == len1) possibilities = false;
                }
                if(possibilities) len = Math.max(len, str.length());
            }
        }

        return len;
    }
}",0,leetcode,NA,JAVA
,"import java.util.Arrays;
import java.util.List;
public class StreamExample {
    public static int sumSquares(List<Integer> numbers) {
        return numbers.stream()
            .filter(n -> n % 2 == 0)
            .map(n -> n * n)
            .reduce(0, Integer::sum);
    }
}
",1,PERPLEXITY,"""Write Java stream operations to filter even numbers, map to squares, and reduce to sum.",JAVA
,"class Solution {
    int i=0,j=0;
     int m=0;int n=0;

    public Solution(int m, int n) {
        this.m=m;
        this.n=n;
    }
    
    public int[] flip() {
        j++;
        if(j==n){
            j=0;
            i++;
        }
        if(i==m){
            i=0;
            j=0;
        }

             
        return new int[]{i,j};
        
    }
    
    public void reset() {
      
        
        
        
    }
}

/**
 * Your Solution object will be instantiated and called as such:
 * Solution obj = new Solution(m, n);
 * int[] param_1 = obj.flip();
 * obj.reset();
 */",0,leetcode,NA,JAVA
,"import java.util.*;

class Solution {
    public List<String> subdomainVisits(String[] cpdomains) {
        Map<String, Integer> map = new HashMap<>();

        for (String domainCount : cpdomains) {
            int spaceIndex = domainCount.indexOf(' ');
            int count = Integer.parseInt(domainCount.substring(0, spaceIndex));
            String domain = domainCount.substring(spaceIndex + 1);

            // Process each subdomain
            while (true) {
                map.merge(domain, count, Integer::sum);
                int dotIndex = domain.indexOf('.');
                if (dotIndex == -1) break;
                domain = domain.substring(dotIndex + 1);
            }
        }

        List<String> result = new ArrayList<>(map.size());
        for (Map.Entry<String, Integer> entry : map.entrySet()) {
            result.add(entry.getValue() + "" "" + entry.getKey());
        }

        return result;
    }
}",0,leetcode,NA,JAVA
,"class Solution {
    public List<String> topKFrequent(String[] words, int k) {
        Map<String,Integer> map = new HashMap<>();
        for(String ch:words){
            map.put(ch,map.getOrDefault(ch,0)+1);
        }

        PriorityQueue<Pair> pq = new PriorityQueue<>((a,b) -> {
            if(a.freq!=b.freq){
                return b.freq - a.freq;
            }

            return a.ch.compareTo(b.ch);
        });

        for (Map.Entry<String, Integer> entry : map.entrySet()) {
            pq.add(new Pair(entry.getKey(), entry.getValue()));
        }

        List<String> ans = new ArrayList<>();
        while(!pq.isEmpty() && k >0){
            Pair curr = pq.poll();
            ans.add(curr.ch);
            k--;
        }

        return ans;
    }
}

class Pair{
    String ch;
    int freq;
    Pair(String ch,int freq){
        this.ch = ch;
        this.freq = freq;
    }
}",0,leetcode,NA,JAVA
,"import java.util.*;
public class LambdaComparator {
    public static void sortStrings(List<String> list) {
        list.sort((s1, s2) -> {
            if (s1.length() != s2.length()) 
                return s1.length() - s2.length();
            return s1.compareTo(s2);
        });
    }
}
",1,PERPLEXITY,Create a lambda comparator to sort a list of strings by length then alphabetically.,JAVA
,"class Solution {
    public int minStickers(String[] stickers, String target) {
        int n = stickers.length;

        target = sortChars(target);
        for (int i = 0; i < n; ++i) stickers[i] = sortChars(stickers[i]);

        Queue<String> q = new LinkedList();
        q.offer(target);
        int steps = 0;
        Set<String> visited = new HashSet<>();
        while (!q.isEmpty()) {
            steps++;
            int size = q.size();
            while(size-- > 0) {
                String x = q.poll();
                for (int i = 0; i < n; ++i) {
                    String now = filter(x, stickers[i]);
                    if (now.isEmpty()) return steps;
                    if (!now.equals(x) && !visited.contains(now)) {
                        visited.add(now);
                        q.offer(now);
                    }
                }
            }
        }
        return -1;
    }
    public String filter(String a, String b) {
        StringBuilder ret = new StringBuilder();
        int idx = 0;

        for (char c : a.toCharArray()) {
            boolean found = false;
            while (idx < b.length() && b.charAt(idx) <= c) {
                if (b.charAt(idx++) == c) {
                    found = true;
                    break;
                }
            }
            if (!found) ret.append(c);
        }
        return ret.toString();
    }
    private String sortChars(String s) {
        char[] chars = s.toCharArray();
        Arrays.sort(chars);
        return new String(chars);
    }
}
",0,leetcode,NA,JAVA
,"import java.util.Optional;
public class OptionalExample {
    public static String getEmail(User user) {
        return Optional.ofNullable(user)
            .map(User::getEmail)
            .filter(email -> !email.isEmpty())
            .orElse(""no-email@domain.com"");
    }
}
class User { private String email; public String getEmail() { return email; } }
",1,PERPLEXITY,Write Java code using Optional to safely extract user email or return defaul,JAVA
,"class Solution {
    public int getImportance(List<Employee> employees, int id) {
        Map<Integer, Employee> inputMap = new HashMap<>();
                // Construct HashMap as getting the employee from id is difficult in a list
                for(Employee e : employees) {
                        inputMap.put(e.id, e);
                }
                return helper(inputMap, id);
        }

        private static int helper(Map<Integer, Employee> inputMap, int id) {
                //Get the importance of the employee
                int imp = inputMap.get(id).importance;
                
                //Add importance of subordinates to employee importance
                for(int subId : inputMap.get(id).subordinates) {
                        imp += helper(inputMap, subId);
                }
                
                return imp;
        }
}",0,leetcode,NA,JAVA
,"import java.util.*;
import java.util.stream.Collectors;
public class GroupingExample {
    public static Map<String, List<Employee>> groupByDept(List<Employee> employees) {
        return employees.stream()
            .collect(Collectors.groupingBy(Employee::getDepartment));
    }
}
class Employee { private String department; public String getDepartment() { return department; } }
",1,PERPLEXITY,Use Java Collectors.groupingBy to group list of employees by department,JAVA
,"class MapSum {
    Map<String, Integer> map;

    public MapSum() {
        map = new HashMap<>();
    }
    
    public void insert(String key, int val) {
        map.put(key, val);
    }
    
    public int sum(String prefix) {
        int sum = 0;
        for (String key : map.keySet()) {
            if (key.startsWith(prefix)) {
                sum += map.get(key);
            }
        }
        return sum;
    }
}",0,leetcode,NA,JAVA
,"import java.util.List;
public class ParallelStreamExample {
    public static long sumSquaresParallel(List<Integer> numbers) {
        return numbers.parallelStream()
            .mapToLong(n -> (long) n * n)
            .sum();
    }
}
",1,PERPLEXITY,Calculate sum of squares using parallel streams on a large list of numbers,JAVA
,"class MagicDictionary {
    Set<String> originalWords;
    Map<String, Integer> extensions;

    public MagicDictionary() {
        originalWords = new HashSet<>();
        extensions = new HashMap<>();
    }
    
    public void buildDict(String[] dictionary) {
        for (String word : dictionary) {
            originalWords.add(word);
            char[] str = word.toCharArray();
            int n = str.length;
            for (int i = 0; i < n; i++) {
                char temp = str[i];
                str[i] = '*';
                String key = new String(str);
                extensions.put(key, extensions.getOrDefault(key, 0) + 1);
                str[i] = temp;
            }
        }
    }
    
    public boolean search(String searchWord) {
        char[] str = searchWord.toCharArray();
        int n = str.length;
        for (int i = 0; i < n; i++) {
            char temp = str[i];
            str[i] = '*';
            String key = new String(str);
            if (extensions.containsKey(key)) {
                // If count >= 2, then there's definitely a different word that maps to this pattern
                // If count == 1, make sure it's not the same word
                if (extensions.get(key) >= 2 || !originalWords.contains(searchWord)) {
                    return true;
                }
            }
            str[i] = temp;
        }
        return false;
    }
}",0,leetcode,NA,JAVA
,"class Solution {
    public boolean isPossible(int[] nums) {
        // freq: counts how many of each number are available to be used
        Map<Integer, Integer> freq = new HashMap<>();
        // want: counts how many sequences are currently ending at (x-1) and need 'x'
        Map<Integer, Integer> want = new HashMap<>();

        for (int i : nums) freq.put(i, freq.getOrDefault(i, 0) + 1);

        for (int i : nums) {
            if (freq.get(i) == 0) continue; // Already consumed by a previous 'new sequence' check

            // Option 1: Try to extend an existing sequence
            if (want.getOrDefault(i, 0) > 0) {
                freq.put(i, freq.get(i) - 1);
                want.put(i, want.get(i) - 1);
                want.put(i + 1, want.getOrDefault(i + 1, 0) + 1);
            } 
            // Option 2: Try to create a new sequence of length 3
            else if (freq.getOrDefault(i + 1, 0) > 0 && freq.getOrDefault(i + 2, 0) > 0) {
                freq.put(i, freq.get(i) - 1);
                freq.put(i + 1, freq.get(i + 1) - 1);
                freq.put(i + 2, freq.get(i + 2) - 1);
                // This sequence now ends at i+2, so it looks forward to i+3
                want.put(i + 3, want.getOrDefault(i + 3, 0) + 1);
            } 
            // Option 3: Impossible to use 'i' validly
            else {
                return false;
            }
        }
        return true;
    }
}",0,leetcode,NA,JAVA
,"public enum DayOfWeek {
    MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY;
    
    public static DayOfWeek[] values() {
        return values();
    }
    
    public static DayOfWeek getByName(String name) {
        for (DayOfWeek day : values()) {
            if (day.name().equalsIgnoreCase(name)) return day;
        }
        throw new IllegalArgumentException(""Invalid day: "" + name);
    }
}
",1,PERPLEXITY,Create a Java enum for days of week with a custom values method and getByName,JAVA
,"class Solution {
    HashSet<Integer> set = new HashSet<>();

    public boolean findTarget(TreeNode root, int k) {
        // Base case: null node
        if (root == null) return false;

        // If complement is found, return true
        if (set.contains(k - root.val)) return true;

        // Otherwise, add current node value to the set
        set.add(root.val);

        // Recurse on left and right subtrees
        return findTarget(root.left, k) || findTarget(root.right, k);
    }
}",0,leetcode,NA,JAVA
,"public class ValidationException extends Exception {
    public ValidationException(String message) { super(message); }
}
public class UserValidationException extends ValidationException {
    public UserValidationException(String field) {
        super(""Invalid "" + field + "" value provided"");
    }
}
public class Validator {
    public static void validateEmail(String email) throws UserValidationException {
        if (!email.contains(""@"")) throw new UserValidationException(""email"");
    }
}
",1,PERPLEXITY,Define a custom exception class hierarchy with validation exception in Java,JAVA
,"class Solution {
    public List<TreeNode> findDuplicateSubtrees(TreeNode root) {
        List<TreeNode> res=new ArrayList<>();
        HashMap<String,Integer> hm=new HashMap<>();
        helper(res,root,hm);
        return res;
    }
    public String helper(List<TreeNode> res,TreeNode root,HashMap<String,Integer> hm){
        if(root==null)
            return """";
        String left=helper(res,root.left,hm);
        String right=helper(res,root.right,hm);
        int currroot=root.val;
        String stringformed=currroot+""$""+left+""$""+right;
        if(hm.getOrDefault(stringformed,0)==1){
            res.add(root);
        }
        hm.put(stringformed,hm.getOrDefault(stringformed,0)+1);
        return stringformed;
    }
}",0,leetcode,NA,JAVA
,"import java.lang.reflect.Field;
public class ReflectionUtil {
    public static void setPrivateField(Object obj, String fieldName, Object value) throws Exception {
        Field field = obj.getClass().getDeclaredField(fieldName);
        field.setAccessible(true);
        field.set(obj, value);
    }
    public static Object getPrivateField(Object obj, String fieldName) throws Exception {
        Field field = obj.getClass().getDeclaredField(fieldName);
        field.setAccessible(true);
        return field.get(obj);
    }
}
",1,PERPLEXITY,Write Java reflection code to access and modify private fields dynamically.,JAVA
,"class Solution {
    Trie root;
    public String replaceWords(List<String> dictionary, String sentence) {
        root = new Trie();
        for(String word : dictionary){
            insert(word);
        }
        StringBuilder result = new StringBuilder();
        String []  input = sentence.split("" "");
        for(String i : input){
            result.append(search(i));
            result.append("" "");
        }
        return result.toString().trim();
    }
    public String search(String word){
        Trie node = root;
        int j = 0;
        for(char c : word.toCharArray()){
            int i = c - 'a';
            j++;
            if(node.children[i] == null){
                return word;
            }else if(node.children[i].isEnd){
                return word.substring(0, j);
            }else{
                node = node.children[i];
            }
            
        }
        return word;

    }
    public void insert(String word){
        Trie node = root;
        for(char c: word.toCharArray()){
            int i = c - 'a';
            if(node.children[i] == null){
                node.children[i] = new Trie();
            }
            node = node.children[i];
        }
        node.isEnd = true;
    }
}
class Trie{
    Trie [] children;
    boolean isEnd;
    public Trie(){
        children = new Trie[26];
        isEnd =false;
    }
} ",0,leetcode,NA,JAVA
,"import java.util.List;
public class GenericUtils {
    public static void printList(List<?> list) {
        for (Object item : list) System.out.println(item);
    }
    public static void addNumbers(List<? super Integer> list) {
        list.add(42);
    }
    public static double sum(List<? extends Number> numbers) {
        double sum = 0;
        for (Number n : numbers) sum += n.doubleValue();
        return sum;
    }
}
",1,PERPLEXITY,Create generic methods using wildcards for super and extends in Java collections,JAVA
,"

class Solution {
    public int[] findErrorNums(int[] nums) {
        int dup = -1, missing = -1;
        
        for (int i = 1; i <= nums.length; i++) {
            int count = 0;
            for (int j = 0; j < nums.length; j++) {
                if (nums[j] == i) {
                    count++;
                }
            }
            if (count == 2) {
                dup = i;
            } else if (count == 0) {
                missing = i;
            }
        }
        
        return new int[] {dup, missing};
    }
}

",0,leetcode,NA,JAVA
,"import java.lang.annotation.*;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface LogExecution {
    String value() default """";
}
public class AnnotationProcessor {
    public static void process(Object obj) throws Exception {
        for (java.lang.reflect.Method m : obj.getClass().getMethods()) {
            if (m.isAnnotationPresent(LogExecution.class)) {
                System.out.println(""Logging: "" + m.getName());
            }
        }
    }
}
",1,PERPLEXITY,Create a basic custom annotation with processor stub for runtime processing,JAVA
,"class Solution {
    public int[] smallestRange(List<List<Integer>> nums) {
        // Min-Heap: stores (value, list index, element index)
        PriorityQueue<int[]> minHeap = new PriorityQueue<>((a, b) -> a[0] - b[0]);
        int curMax = Integer.MIN_VALUE;

        // Initialize the heap with the first element of each list
        for (int i = 0; i < nums.size(); i++) {
            minHeap.offer(new int[]{nums.get(i).get(0), i, 0});
            curMax = Math.max(curMax, nums.get(i).get(0));
        }

        // Track the smallest range
        int[] smallRange = new int[]{0, Integer.MAX_VALUE};

        while (true) {
            // Get the minimum element from the heap
            int[] curr = minHeap.poll();
            int curMin = curr[0], listIdx = curr[1], elemIdx = curr[2];

            // Update the smallest range if a better one is found
            if (curMax - curMin < smallRange[1] - smallRange[0]) {
                smallRange[0] = curMin;
                smallRange[1] = curMax;
            }

            // Move to the next element in the same list
            if (elemIdx + 1 < nums.get(listIdx).size()) {
                int nextVal = nums.get(listIdx).get(elemIdx + 1);
                minHeap.offer(new int[]{nextVal, listIdx, elemIdx + 1});
                curMax = Math.max(curMax, nextVal);
            } else {
                // If any list is exhausted, stop
                break;
            }
        }
        return smallRange;
    }
}",0,leetcode,NA,JAVA
,"class Solution {
    public boolean isSubsequence(String s1, String s2) {
        int m = s1.length();
        int n = s2.length();
        int j=0,i=0;
        while(i<m){
            if(j>=n) return true;
            if(s1.charAt(i)==s2.charAt(j)){
                i++;
                j++;
            }
            else i++;
        }
        if(j>=n) return true;
        return false;
    }
    public int numMatchingSubseq(String s1, String[] words) {
        int count = 0;
        HashMap<String, Integer> map = new HashMap<>();
        for (String w : words) map.put(w, map.getOrDefault(w, 0) + 1);

        for(String s2 : map.keySet()){
            if(isSubsequence(s1,s2)) count+=map.get(s2);
        }
        return count;
    }
}",0,leetcode,NA,JAVA
,"class Solution {
    public int leastInterval(char[] tasks, int n) {
        int[] freq = new int[26];
        for (char task : tasks) {
            freq[task - 'A']++;
        }
        Arrays.sort(freq);
        int chunk = freq[25] - 1;
        int idle = chunk * n;

        for (int i = 24; i >= 0; i--) {
            idle -= Math.min(chunk, freq[i]);
        }

        return idle < 0 ? tasks.length : tasks.length + idle;
    }
}",0,leetcode,NA,JAVA
,"class Solution {
    public List<List<String>> findDuplicate(String[] paths) {
        List<List<String>> al = new ArrayList<>();
        HashMap<String, List<String>> hashmap = new HashMap<>();
        for(String path : paths) {
            String[] arr = path.split(""\\ "");
            String dirPath = arr[0];
            for(int i = 1; i < arr.length; i++) {
                StringBuilder content = new StringBuilder();
                int j = 0;
                for(j = arr[i].length() - 2; j >= 0 && arr[i].charAt(j) != '('; j--) {
                    content.insert(0, arr[i].charAt(j));
                }
                
                String fileName = arr[i].substring(0, j);
                hashmap.putIfAbsent(content.toString(), new ArrayList<>());
                hashmap.get(content.toString()).add(dirPath + ""/"" + fileName);
            }
        }
        
        for(String string : hashmap.keySet()) {
            if(hashmap.get(string).size() >= 2) {
                al.add(new ArrayList<>(hashmap.get(string)));
            }
        }
        return al;
    }
}",0,leetcode,NA,JAVA
,"public int evaluate(String expression) 
{
    return eval(expression, new HashMap<>());
}

private int eval(String expr, Map<String, Integer> scope) 
{
    // 1. If it's a number, return it directly
    if (Character.isDigit(expr.charAt(0)) || expr.charAt(0) == '-') 
        return Integer.parseInt(expr);

    // 2. If it's a variable, get its value from the scope
    if (Character.isLowerCase(expr.charAt(0)) && !expr.startsWith(""("")) 
        return scope.get(expr);     //e.g. scope={ ""x"": 2, ""y"": 3 }  so return 2 for eval(x, scope)

    // 3. Remove outer parentheses and tokenize the expression
    expr=expr.substring(1, expr.length() - 1); // Remove outer parentheses
    List<String> tokens = new ArrayList<>();
    int balance=0, start=0;

    for (int i=0; i<expr.length(); i++) {
        char c=expr.charAt(i);
        if (c=='(') balance++;
        if (c==')') balance--;
        if (balance==0 && (c==' '||i==expr.length()-1)) 
        {//Splits tokens when we hit a space (c == ' ') or reach the last character (i == expr.length() - 1
            tokens.add(expr.substring(start, i+(i==expr.length()-1?1:0)).trim());     //If the current character is the last one, extend the substring to include it (i + 1).
            start=i+1;
        }
    }
    //e.g. tokens = [""let"", ""x"", ""2"", ""(mult x (let x 3 y 4 (add x y)))""];
    // 4. Parse operation and evaluate accordingly
    String operation = tokens.get(0);
    if (operation.equals(""add"")) 
        return eval(tokens.get(1), scope) + eval(tokens.get(2), scope);
    else if (operation.equals(""mult""))   //tokens = [""mult"", ""x"", ""(let x 3 y 4 (add x y))""];
        return eval(tokens.get(1), scope) * eval(tokens.get(2), scope);     //get x val * get val of the other expr
    else                // ""let"" operation
    { 
        Map<String, Integer> newScope = new HashMap<>(scope); // Create a new scope // Scope: {}
        for (int i=1;i<tokens.size()-1;i+=2) 
            newScope.put(tokens.get(i), eval(tokens.get(i+1), newScope)); // Assign variables - newScope.put(""x"", eval(""2"", newScope)); // x = 2
        return eval(tokens.get(tokens.size()-1), newScope); // Evaluate the final expression - eval(""(mult x (let x 3 y 4 (add x y)))"", newScope);

    }
}",0,leetcode,NA,JAVA
,"import java.net.http.*;
import java.net.URI;
import com.fasterxml.jackson.databind.ObjectMapper;
public class RestClient {
    public static <T> T getJson(String url, Class<T> clazz) throws Exception {
        HttpClient client = HttpClient.newHttpClient();
        HttpRequest req = HttpRequest.newBuilder(URI.create(url)).GET().build();
        HttpResponse<String> resp = client.send(req, HttpResponse.BodyHandlers.ofString());
        ObjectMapper mapper = new ObjectMapper();
        return mapper.readValue(resp.body(), clazz);
    }
}
",1,PERPLEXITY,Write Java code using HttpClient to call REST API and parse JSON response.,JAVA
,"class Solution {
    public String countOfAtoms(String formula) {
        int n = formula.length();
        Map<String, Integer> result_counter = new HashMap<>();
        Deque<Map<String, Integer>> parenthesis_stack = new ArrayDeque<>();
        int cur_ind = 0;

        while (cur_ind < n) {
            char cur_char = formula.charAt(cur_ind);

            if (cur_char == '(') {
                cur_ind++;
                parenthesis_stack.push(new HashMap<>());
                continue;
            }

            if (cur_char == ')') {
                StringBuilder mult_str = new StringBuilder();
                cur_ind++;

                while (cur_ind < n && Character.isDigit(formula.charAt(cur_ind))) {
                    mult_str.append(formula.charAt(cur_ind));
                    cur_ind++;
                }

                int mult = mult_str.length() == 0 ? 1 : Integer.parseInt(mult_str.toString());
                Map<String, Integer> last_counter = parenthesis_stack.pop();
                Map<String, Integer> target = parenthesis_stack.isEmpty() ? result_counter : parenthesis_stack.peek();
                
                for (Map.Entry<String, Integer> entry : last_counter.entrySet()) {
                    target.put(entry.getKey(), target.getOrDefault(entry.getKey(), 0) + entry.getValue() * mult);
                }
                continue;
            }

            StringBuilder cur_elem = new StringBuilder();
            StringBuilder cur_counter_str = new StringBuilder();
            Map<String, Integer> target = parenthesis_stack.isEmpty() ? result_counter : parenthesis_stack.peek();

            while (cur_ind < n && formula.charAt(cur_ind) != '(' && formula.charAt(cur_ind) != ')') {
                if (Character.isAlphabetic(formula.charAt(cur_ind))) {
                    if (Character.isUpperCase(formula.charAt(cur_ind)) && cur_elem.length() > 0) {
                        target.put(cur_elem.toString(), target.getOrDefault(cur_elem.toString(), 0) + (cur_counter_str.length() == 0 ? 1 : Integer.parseInt(cur_counter_str.toString())));
                        cur_elem = new StringBuilder();
                        cur_counter_str = new StringBuilder();
                    }
                    cur_elem.append(formula.charAt(cur_ind));
                } else {
                    cur_counter_str.append(formula.charAt(cur_ind));
                }
                cur_ind++;
            }

            target.put(cur_elem.toString(), target.getOrDefault(cur_elem.toString(), 0) + (cur_counter_str.length() == 0 ? 1 : Integer.parseInt(cur_counter_str.toString())));
        }

        List<String> parts = new ArrayList<>();
        for (Map.Entry<String, Integer> entry : result_counter.entrySet()) {
            parts.add(entry.getKey() + (entry.getValue() == 1 ? """" : entry.getValue()));
        }
        Collections.sort(parts);

        StringBuilder result = new StringBuilder();
        for (String part : parts) {
            result.append(part);
        }

        return result.toString();
    }
}",0,leetcode,NA,JAVA
,"import java.sql.*;
import java.util.*;
public class JdbcPool {
    private List<Connection> pool = new ArrayList<>();
    private int maxSize;
    
    public JdbcPool(int maxSize) { this.maxSize = maxSize; }
    
    public Connection getConnection() throws SQLException {
        if (pool.isEmpty()) {
            return DriverManager.getConnection(""jdbc:h2:mem:test"");
        }
        return pool.remove(0);
    }
    
    public void returnConnection(Connection conn) {
        pool.add(conn);
    }
}
",1,PERPLEXITY,Implement a simple JDBC connection pool manager in Java.,JAVA
,"class Solution {

    /*
     * Disjoint Set Union over emails.
     * Each unique email is treated as a node.
     */
    static class DSU {
        int[] parent;
        int[] size;

        /*
         * Initializes DSU with each email in its own set.
         */
        DSU(int n) {
            parent = new int[n];
            size = new int[n];

            for (int i = 0; i < n; i++) {
                parent[i] = i;
                size[i] = 1;
            }
        }

        /*
         * Returns representative of the email's component.
         * Uses path compression to keep tree shallow.
         */
        int find(int x) {
            if (parent[x] != x) {
                parent[x] = find(parent[x]);
            }
            return parent[x];
        }

        /*
         * Merges two email components using union by size.
         */
        void union(int a, int b) {
            int pa = find(a);
            int pb = find(b);

            if (pa == pb)
                return;

            if (size[pa] < size[pb]) {
                parent[pa] = pb;
                size[pb] += size[pa];
            } else {
                parent[pb] = pa;
                size[pa] += size[pb];
            }
        }
    }

    /*
     * Merges accounts that share at least one common email.
     * Emails in the result are sorted lexicographically.
     */
    public List<List<String>> accountsMerge(List<List<String>> accounts) {

        /*
         * Maps each email to a unique DSU index.
         * Also keeps track of the owner name for each email.
         */
        Map<String, Integer> emailIndex = new HashMap<>();
        Map<String, String> emailName = new HashMap<>();

        int idx = 0;

        for (List<String> acc : accounts) {
            String name = acc.get(0);

            for (int i = 1; i < acc.size(); i++) {
                String email = acc.get(i);

                if (!emailIndex.containsKey(email)) {
                    emailIndex.put(email, idx++);
                    emailName.put(email, name);
                }
            }
        }

        DSU dsu = new DSU(idx);

        /*
         * Union all emails belonging to the same account.
         */
        for (List<String> acc : accounts) {
            int firstEmail = emailIndex.get(acc.get(1));

            for (int i = 2; i < acc.size(); i++) {
                dsu.union(firstEmail, emailIndex.get(acc.get(i)));
            }
        }

        /*
         * Groups emails by their DSU representative.
         */
        Map<Integer, List<String>> groups = new HashMap<>();

        for (String email : emailIndex.keySet()) {
            int root = dsu.find(emailIndex.get(email));
            groups.computeIfAbsent(root, k -> new ArrayList<>()).add(email);
        }

        /*
         * Builds the final merged account list.
         */
        List<List<String>> result = new ArrayList<>();

        for (List<String> emails : groups.values()) {
            Collections.sort(emails);

            List<String> merged = new ArrayList<>();
            merged.add(emailName.get(emails.get(0)));
            merged.addAll(emails);

            result.add(merged);
        }

        return result;
    }
}",0,leetcode,NA,JAVA

,"import java.net.*;
import java.io.*;
public class EchoServer {
    public static void main(String[] args) throws IOException {
        ServerSocket server = new ServerSocket(8080);
        while (true) {
            Socket client = server.accept();
            new Thread(() -> {
                try (BufferedReader in = new BufferedReader(
                    new InputStreamReader(client.getInputStream()));
                     PrintWriter out = new PrintWriter(client.getOutputStream(), true)) {
                    String line;
                    while ((line = in.readLine()) != null) {
                        out.println(""Echo: "" + line);
                    }
                } catch (IOException e) {}
            }).start();
        }
    }
}
",1,PERPLEXITY,Create a simple TCP socket server in Java that echoes client messages,JAVA

,"class Solution {
        private TreeNode root;
        private String result = """";

        public String longestWord(String[] words) {
                root = new TreeNode();

                for (String w : words)
                        insert(w);

                dfs(root);

                return result;
        }

        private void dfs(TreeNode node) {
                if (node == null)
                        return;

                if (node.word != null) {
                        if (node.word.length() > result.length())
                                result = node.word;
                        else if (node.word.length() == result.length() && node.word.compareTo(result) < 0)
                                result = node.word;
                }

                for (TreeNode child : node.children)
                        if (child != null && child.word != null)
                                dfs(child);
        }

        private void insert(String word) {
                TreeNode current = root;
                for (char c : word.toCharArray()) {
                        if (current.children[c - 'a'] == null)
                                current.children[c - 'a'] = new TreeNode();
                        current = current.children[c - 'a'];
                }
                current.word = word;
        }

}

class TreeNode {
        TreeNode[] children = new TreeNode[26];
        String word;

        TreeNode () {}
}",0,leetcode,NA,JAVA

,"import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugins.annotations.*;
@Mojo(name = ""generate-props"", defaultPhase = LifecyclePhase.GENERATE_RESOURCES)
public class PropertiesGeneratorMojo extends AbstractMojo {
    @Parameter(defaultValue = ""${project.build.directory}"")
    private String outputDirectory;
    
    public void execute() throws MojoExecutionException {
        getLog().info(""Generating properties file..."");
        // Generate properties logic here
        getLog().info(""Properties file generated successfully"");
    }
}
",1,PERPLEXITY,Write a basic Maven plugin MOJO class that generates a properties file.,JAVA

,"class Solution {

    List <int[]> dividedRange;
    int numberOfDivisions = 0;
    Random rand;
    public Solution(int n, int[] arr) {
        Arrays.sort(arr);
        rand = new Random();
        dividedRange = new ArrayList <>();
        int start = 0, end = 0;
        for (int i = 0; i < arr.length; i++) {
            end = arr[i] - 1;
            if (start > end) {
                start = arr[i] + 1;
                continue;
            }
            dividedRange.add(new int[]{start, end});
            start = arr[i] + 1;
        }
        if (start < n) {
            dividedRange.add(new int[]{start, n-1});
        } 
        numberOfDivisions = dividedRange.size();
    }
    
    public int pick() {
        int pickedDivision = rand.nextInt(numberOfDivisions);
        int start = dividedRange.get(pickedDivision)[0];
        int end = dividedRange.get(pickedDivision)[1];
        return rand.nextInt(end - start + 1) + start;
    }
}

/**
 * Your Solution object will be instantiated and called as such:
 * Solution obj = new Solution(n, blacklist);
 * int param_1 = obj.pick();
 */",0,leetcode,NA,JAVA

,"class Node {
    int key;
    int val;
    Node next;

    Node(int key, int val) {
        this.key = key;
        this.val = val;
        this.next = null;
    }
}

class MyHashMap {

    private Node[] map;

    public MyHashMap() {
        map = new Node[1000];
        for (int i = 0; i < 1000; i++) {
            map[i] = new Node(-1, -1);
        }
    }

    public void put(int key, int value) {
        int hash = hash(key);
        Node cur = map[hash];

        while (cur.next != null) {
            if (cur.next.key == key) {
                cur.next.val = value;
                return;
            }
            cur = cur.next;
        }

        cur.next = new Node(key, value);
    }

    public int get(int key) {
        int hash = hash(key);
        Node cur = map[hash].next;

        while (cur != null) {
            if (cur.key == key)
                return cur.val;
            cur = cur.next;
        }

        return -1;
    }

    public void remove(int key) {
        int hash = hash(key);
        Node cur = map[hash];

        while (cur.next != null) {
            if (cur.next.key == key) {
                cur.next = cur.next.next;
                return;
            }
            cur = cur.next;
        }
    }

    private int hash(int key) {
        return key % 1000;
    }
}

/**
 * Your MyHashMap object will be instantiated and called as such:
 * MyHashMap obj = new MyHashMap();
 * obj.put(key,value);
 * int param_2 = obj.get(key);
 * obj.remove(key);
 */",0,leetcode,NA,JAVA

,"import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping(""/api/users"")
public class UserController {
    @GetMapping(""/{id}"")
    public String getUser(@PathVariable Long id) {
        return ""User: "" + id;
    }
    
    @PostMapping
    public String createUser(@RequestBody String name) {
        return ""Created user: "" + name;
    }
}
",1,PERPLEXITY,"Create a basic Spring Boot REST controller with GET, POST endpoints.",JAVA

,"package SystemDesign.Easy;

public class _705_Design_HashSet {

    // Custom HashSet implementation using bitset
    private static class MyHashSet {

        // Each int holds 32 bits → supports keys up to 10^6
        private final int[] set;

        public MyHashSet() {
            // 10^6 / 32 ≈ 31250
            this.set = new int[31251];
        }

        public void add(int key) {
            set[key / 32] |= getMask(key);
        }

        public void remove(int key) {
            if (contains(key)) {
                set[key / 32] ^= getMask(key);
            }
        }

        public boolean contains(int key) {
            return (set[key / 32] & getMask(key)) != 0;
        }

        // Returns a bit mask for the given key
        private int getMask(int key) {
            return 1 << (key % 32);
        }
    }
}",0,leetcode,NA,JAVA

,"class Solution {
    public int findShortestSubArray(int[] nums) {

        HashMap<Integer, Integer> count = new HashMap<>();
        HashMap<Integer, Integer> first = new HashMap<>();
        HashMap<Integer, Integer> last = new HashMap<>();

        for (int i = 0; i < nums.length; i++) {
            int num = nums[i];

            count.put(num, count.getOrDefault(num, 0) + 1);

            if (!first.containsKey(num)) {
                first.put(num, i);
            }
            last.put(num, i);
        }

        int degree = 0;
        for (int val : count.values()) {
            degree = Math.max(degree, val);
        }

        int ans = nums.length;
        for (int key : count.keySet()) {
            if (count.get(key) == degree) {
                ans = Math.min(ans, last.get(key) - first.get(key) + 1);
            }
        }

        return ans;
    }
}",0,leetcode,NA,JAVA

,"import java.util.HashMap;

class Solution {
    public String customSortString(String order, String s) {
        StringBuilder result = new StringBuilder();
        HashMap<Character, Integer> mp = new HashMap<>();
        for (char c : s.toCharArray()) {
            mp.put(c, mp.getOrDefault(c, 0) + 1);
        }
        for (char c : order.toCharArray()) {
            if (mp.containsKey(c)) {
                result.append(String.valueOf(c).repeat(Math.max(0, mp.get(c))));
                mp.remove(c);
            }
        }
        for (char c : mp.keySet()) {
            result.append(String.valueOf(c).repeat(Math.max(0, mp.get(c))));
        }
        return result.toString();
    }
}",0,leetcode,NA,JAVA

,"class Solution {
    public int numRabbits(int[] answers) {
        Map<Integer, Integer> mpp = new HashMap<>();
        for (int i : answers) mpp.put(i, mpp.getOrDefault(i, 0) + 1);

        int total = 0;
        for (Map.Entry<Integer, Integer> p : mpp.entrySet())
            total += Math.ceil((double)p.getValue() / (p.getKey() + 1)) * (p.getKey() + 1);

        return total;
    }
}",0,leetcode,NA,JAVA